0

我有一个节点喜欢表,大致如下所示:

lid nid uid type
1   23  3   like
2   23  1   like
3   49  3   dislike
4   11  6   like

lid = 此表的唯一 ID,nid =“节点”(内容)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

我可以得到每个节点的喜欢和不喜欢分数。内连接无关紧要;一些(不)喜欢来自不再存在的用户,加入是为了消除它们。

结果如下所示:

nid score type
307 4     like
307 1     dislike
404 24    like

然后如何按 对这个查询进行分组type,并返回每个“喜欢”类型(喜欢/不喜欢)的得分最高的节点 ID?

IE。

nid score type
404 24    like
307 1     dislike
4

3 回答 3

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
于 2012-07-24T18:00:52.987 回答
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
于 2012-07-24T17:58:51.330 回答
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; 

可能会成功。

于 2012-07-24T17:52:33.327 回答