Is there any MySQL Aggregate Function for “CONTAINS”?

旧城冷巷雨未停 提交于 2019-12-05 11:28:54

The right way to do it:

SELECT
   user,
   IF(SUM(group = 'A'), TRUE, FALSE) AS IN_A,
   IF(SUM(group = 'B'), TRUE, FALSE) AS IN_B,
   IF(SUM(group = 'C'), TRUE, FALSE) AS IN_C
FROM users
GROUP BY user

I guess this is the only way i.e., GROUP_CONCAT

You can try something like this piece:

SELECT distinct user,  
IF(EXISTS
    (SELECT users_a.user 
        from users as users_a 
    where users_a.group = 'A' and
        users_a.user = users.user), 
TRUE, FALSE) as IN_A,
IF(EXISTS
    (SELECT users_b.user 
        from users as users_b 
    where users_b.group = 'B' and
        users_b.user = users.user), 
TRUE, FALSE) as IN_B,
IF(EXISTS
    (SELECT users_c.user 
        from users as users_c 
    where users_c.group = 'C' and
        users_c.user = users.user), 
TRUE, FALSE) as IN_C
FROM `users` WHERE 1

Tryed here works fine!

Not sure how many groups you will be having but if its a finiate number I would suggest that you create a column for each group or use the mysql data type SET (bit masking).

I'm not sure if this is the way you do things (as I'm quite new here) but if that's the example you're using wouldn't it be easier to have the columns user, IN_A, IN_B and IN_C? Especially since that way you wouldn't be repeating the user data again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!