简体   繁体   中英

how to order resultset based on fields from two tables

I have two tables one for topic_likes & one for user_comments.I must get recent updates of like & comment from this tables.Given below is the sql :-

SELECT (required fields...)
LEFT JOIN  topic_likes AS TL ON (TL.delete_status=0 AND TL.user_id!=$user_id)
LEFT JOIN  user_comments AS UC ON (UC.delete_status=0 AND UC.user_id!=$user_id)
WHERE
   (TL.created_date >= '$lastLogin' OR UC.created_date >= '$lastLogin' 
ORDER BY UC.created_date desc,TL.created_date desc
LIMIT $limit 

I have given order by two fields from two tables(UC.created_date, TL.created_date) But it does not order the resultset based on created_date from topic_likes.It only orders the results based on user_comments table

But if I removed the limit condition it gives correct results...!!

Any suggestion appreciated

This is a strange approach you're taking. If you want to display user's likes and comments using a single query you should UNION the results. Example:

SELECT * FROM
(
    SELECT id, `date`, 'like' as `type` FROM topic_likes
    UNION 
    SELECT id, `date`, 'comment' as `type` FROM user_comments
) a order by a.date DESC limit 5;

The result should be similar to this:

结果

But there are limitations. The number of columns from each subquery must match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM