在GROUP_CONCAT内搜索

时间:2015-11-09 12:48:51

标签: mysql sql group-by group-concat

我正在从行的大结果

执行此SQL

SELECT userid,group_concat(locationid) 来自user_location 按用户ID分组 有group_concat(locationid)= 10

userid  locationid
---------  ----------
894801  10,10,10,10,10,10,10,10,10,10,10,10
898356  10,10,11,10
900424  10,10,13,12,12,12,12
902123  10
904910  10,10
907922  10,10,10
912587  10,12,12
930319  10

现在,我只想要那些value = 10且没有其他值

的locationid行

期望输出:

userid  locationid
---------  ----------
894801  10,10,10,10,10,10,10,10,10,10,10,10
902123  10
904910  10,10
907922  10,10,10
930319  10

我探索并发现了find_in_set(),但没有在这里使用

2 个答案:

答案 0 :(得分:3)

请勿使用group_concat()的结果。只需使用简单的having子句:

SELECT userid, group_concat(locationid)
FROM user_location
GROUP BY userid 
HAVING SUM(locationid = 10) = COUNT(*)

SUM()计算等于10的值的数量。 = COUNT(*)只是说所有都是10。

您也可以通过确保没有值不是10来执行此操作:

HAVING SUM(locationid <> 10) = 0

答案 1 :(得分:1)

SELECT * FROM user_location WHERE userid not in (select userid from user_location where locationid<>10) 
group by userid having locationid=10;

试试这个..它正在运作

相关问题