2

This issue is on MySQL:

I need to self join the table to get the last record in each group and join that record with another table.

Assume, comments table has 4 columns pkid, session_id, comment, create_date (pkid is the primary key and there will be a number of comments for each session_id)

comment_channel table have session_id, channel (there will be just one row for each session_id)

now I need to get the last comment in each session_id and its channel

So I can write a query something like this:

SELECT t1.session_id, t1.comment, t3.channel, t1.create_date
FROM comments t1
    join (
        SELECT max(pkid)
        FROM comments
        GROUP BY session_id
    ) t2 on t1.pkid = t2.pkid
    left join comment_channel t3 on t1.session_id = t3.session_id

If I want to write this as a view then I can't put the same query because MySQL doesn't support subqueries in VIEW.

so i have to write two views:

View 1:

CREATE OR REPLACE VIEW comment_channel_view AS 
SELECT t1.session_id, t1.comment, t3.channel, t1.create_date FROM comments t1
    join comment_max_id_view t2 on t1.pkid = t2.pkid
    left join comment_channel t3 on t1.session_id = t3.session_id

View 2:

CREATE OR REPLACE VIEW comment_max_id_view AS 
SELECT max(pkid)
FROM comments
GROUP BY session_id

here the problem is, if I use this view to select for a particular period

e.g.

SELECT * FROM comment_channel_view
WHERE create_date between '2019-04-05' and '2019-04-10'

then the comment_max_id_view is doing a full table scan instead of just the selected date range, which takes more than 5 minutes to get the result. If I put the date range condition within the subquery then I am getting the result just in milliseconds.

so what should I do in view to avoid full table scan in comment_max_id_view?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.