假设我有以下mysql查询
SELECT friends.id, sum(if(friends.online =1,1,0)) AS online_friends, ...,...
FROM some_table
GROUP BY id
ORDER BY sum(if(friends.online =1,1,0)) ASC;
我想要的是根据ASC或DESC对online_friends进行排序,问题是这个查询不会被online_friends排序。
有人可以帮我解决问题吗?
这是结果的一个例子
id group online_friends
-- ------- ----------------
1 west 5
2 east 3
3 north 7
4 south 2
我想根据online_friends
对结果进行排序答案 0 :(得分:0)
你可以试试这个:
SELECT friends.id, groups, sum(friends.online) AS online_friends
FROM some_table
where friends.online = 1
GROUP BY friends.id, groups
ORDER BY friends.online ASC;
我认为在线和离线的值分别为1和0。
答案 1 :(得分:0)
您的查询应该有效:
SELECT friends.id, sum(if(friends.online =1,1,0)) AS online_friends, ...,...
FROM friends
GROUP BY id
ORDER BY sum(if(friends.online =1,1,0)) ASC;
但是,我会把它写成:
SELECT friends.id, sum(friends.online = 1) AS online_friends, ...,...
FROM friends
GROUP BY id
ORDER BY sum(friends.online = 1) ASC;
您也可以将order by
更改为:
ORDER BY online_friends
如果您发现它仍然不起作用,请设置一个SQL小提琴,以便我们可以看到发生了什么。