我有一个相当复杂的SQL语句,我正在尝试编写,而不知道该怎么做。
基本上,我正在寻找聊天室中最活跃的人(我的聊天存储在SQL表中),但是减去他们说特定消息TIMES乘以减法的乘数的次数。
这是“基本”查询,可以很好地找出有人聊天的频率:
SELECT users.name, count(*) as count1, users.flag2, users.flag1
FROM chat
INNER JOIN users
ON chat.userid=users.id
WHERE channel=$channel
GROUP BY userid
ORDER BY count DESC
LIMIT 100;
此查询会告诉我用户说出我想要减去 的的特定消息的次数:
SELECT userid, count(*) as count2
FROM chat
WHERE channel=$channel AND text = '[some message]'
GROUP BY userid
我正在寻找的是第一个让“count”实际上等于“ count1 - count2 * 10 ”的查询。我有一个相当艰难的时间来弄清楚如何将这两个查询组合成一个。我将使用生成的“值”作为ORDER BY / LIMIT子句,所以我需要SQL来实际执行此计算而不是在多个查询中执行...
答案 0 :(得分:2)
SELECT T1.name,(count1 - 10* COALESCE( count2,0) ) as NetCount
FROM
(
SELECT userid,users.name, count(*) as count1
FROM chat
INNER JOIN users
ON chat.userid=users.id
WHERE channel=$channel
GROUP BY userid,users.name
ORDER BY count DESC
LIMIT 100;
) as T1
LEFT JOIN
(
SELECT userid, count(*) as count2
FROM chat
WHERE channel=$channel AND text = '[some message]'
GROUP BY userid
) as T2
ON T1.userid=T2.userid