简体   繁体   中英

Search within GROUP_CONCAT

I am executing this SQL from a big result of rows

SELECT userid, group_concat(locationid) FROM user_location group by userid having 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

Now, I want only those locationid rows where the value = 10 and no other value

Desired Output:

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

I explored and found find_in_set() but no use here

Don't use the result from group_concat() . Just use a simple having clause:

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

The SUM() counts the number of values that are equal to 10 . The = COUNT(*) simply says that all are 10.

You can also do this by being sure that no values are not 10:

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

Try this.. It's working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM