我有一个节点喜欢的表,看起来大致如下:
lid nid uid type
1 23 3 like
2 23 1 like
3 49 3 dislike
4 11 6 like
lid =此表的唯一ID,nid =“node”(内容)ID,uid =用户ID和类型是不言自明的。
使用此查询:
SELECT nid, COUNT(lid) AS score, type
FROM node_likes
INNER JOIN users ON node_likes.uid = users.uid
GROUP BY nid, type
我可以让每个节点都有喜欢和不喜欢的分数。内连接是无关紧要的;一些(dis)喜欢来自不再存在的用户,并且联接是为了消除它们。
结果如下:
nid score type
307 4 like
307 1 dislike
404 24 like
如何按type
对此查询进行子分组,并返回每个“喜欢”类型的最高得分节点ID(如/不喜欢)?
即
nid score type
404 24 like
307 1 dislike
答案 0 :(得分:1)
SELECT
SUBSTRING_INDEX(GROUP_CONCAT(nid ORDER BY likes DESC),',',1) as most_likes_nid,
MAX(likes) as most_likes,
SUBSTRING_INDEX(GROUP_CONCAT(nid ORDER BY dislikes DESC),',',1) as most_dislikes_nid,
MAX(dislikes) as most_dislikes
FROM (
SELECT
nid,
COUNT(IF(type = 'like', 1, null)) as likes,
COUNT(IF(type = 'dislike', 1 ,null)) as dislikes
FROM node_likes
GROUP BY nid
) as t
答案 1 :(得分:0)
SELECT nid, COUNT(lid) AS score, type
FROM node_likes
INNER JOIN users ON node_likes.uid = users.uid
GROUP BY nid, type
ORDER BY type DESC, score DESC;
可能会做到这一点。
答案 2 :(得分:0)
试试这个:
SELECT
nid, max(score) as score, type
FROM (
SELECT nid, COUNT(lid) AS score, type
FROM node_likes
INNER JOIN users ON node_likes.uid = users.uid
GROUP BY nid, type
) results
GROUP BY type
ORDER BY type DESC, score DESC