一条关于评论查询并且用户是否点赞的SQL语句

时间:2022-03-09 21:58:07

有一个用户表,一个评论表,还有一个点赞表。
现在需求是查询前十条是按点赞数排序的,后面20条按发表时间排序,然后查询评论内容,以及用户的部分信息,以及当前这个用户是否对该评论点赞了。

**like_comment(点赞表)**
uid         int  
ctime       datetime     
events_id   int 
**user(用户表)**
uid         int  
nickname    varchar  
rid         int  
icons       varchar  
email       varchar  
password    varchar  
sex         char     
birth       date     
city        varchar  
state       int  
ctime       datetime     
introduce   varchar  
note        varchar  
**events(评论表)**
cid         int  
rcid        int  
uid         int  
content     varchar 
likes       int 
feeling     double   
ctime       datetime     

查询的Sql语句:

(SELECT cid,content,like_events.uid as likeid,likes,`user`.nickname as authorname,`events`.uid as authorid,`events`.ctime FROM `events` LEFT JOIN `user` on `user`.uid = `events`.uid LEFT JOIN like_events on events_id = cid AND like_events.uid = 1 ORDER BY likes DESC LIMIT 10) UNION ( SELECT cid,content,like_events.uid as likeid,likes,`user`.nickname as authorname,`events`.uid as authorid,`events`.ctime FROM `events` LEFT JOIN `user` on `user`.uid = `events`.uid LEFT JOIN like_events on events_id = cid AND like_events.uid = 1 ORDER BY `events`.ctime DESC LIMIT 20 )

查询结果中 likeid为空就表示当前用户没有点赞该评论