0

is it possible to using index in unix datetime colum in MySQL 5.7? I define my database table like this:

CREATE TABLE `report_envelope_app_list` (
 `created_time` bigint(20) NOT NULL,
 `user_id` bigint(20) NOT NULL
)

the created_time store unix timestamp,now this is my SQL:

 select max(user_id) as user_id
 from report_user
 group by user_id, date_format(FROM_UNIXTIME(created_time/1000), '%Y-%m-%d')

but now the colum created_time contains function and could not using the index, is it possbible to using index, I have to add a column to store date like %Y-%m-%d? I tried to add a generated column like this:

ALTER TABLE report_user 
ADD COLUMN statistic_date varchar(16) 
GENERATED ALWAYS AS date_format(FROM_UNIXTIME(statistic_time/1000), '%Y-%m-%d') STORED;

but failed.

asked Dec 21, 2020 at 2:21
2
  • date_format(FROM_UNIXTIME(created_time/1000), '%Y-%m-%d') could go into a DATE column Commented Dec 21, 2020 at 6:21
  • Do you really want to both GROUP BY user_id _and` SELECT MAX(user_id)?? Commented Dec 21, 2020 at 6:22

1 Answer 1

1

using generate column and created a index on it:

ALTER TABLE report_user 
ADD COLUMN statistic_date varchar(16) 
GENERATED ALWAYS AS (date_format(FROM_UNIXTIME(statistic_time/1000), '%Y-%m-%d')) STORED;

then created index:

CREATE INDEX report_user_userid_staticdate_idx 
ON report_user(user_id,statistic_date);
answered Dec 21, 2020 at 3:04
1
  • ... then use this generated column in the query instead of the expression. Commented Dec 21, 2020 at 4:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.