是否有“CONTAINS”的MySQL聚合函数?

时间:2010-09-16 10:55:11

标签: sql mysql group-by aggregate-functions

说我有这个数据集

  user  | group
--------+-------
a@a.com |   A
a@a.com |   B
b@b.com |   A
c@c.com |   B
d@d.com |   A
d@d.com |   B
d@d.com |   C

我想将其转换为这样的表:

  user  | IN_A  | IN_B  | IN_C
--------+-------+-------+-------
a@a.com | TRUE  | TRUE  | FALSE
b@b.com | TRUE  | FALSE | FALSE
c@c.com | FALSE | TRUE  | FALSE
d@d.com | TRUE  | TRUE  | TRUE

我有:

SELECT
  user,
  IF(LOCATE('A', GROUP_CONCAT(group)) > 0, TRUE, FALSE) AS IN_A,
  IF(LOCATE('B', GROUP_CONCAT(group)) > 0, TRUE, FALSE) AS IN_B,
  IF(LOCATE('C', GROUP_CONCAT(group)) > 0, TRUE, FALSE) AS IN_C
FROM users
GROUP BY user

我想知道的是,如果有更好的方法来确定聚合字段是否包含值,或者这是唯一的方法吗?

5 个答案:

答案 0 :(得分:12)

正确的方法:

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

答案 1 :(得分:1)

我想这是唯一的方法,即GROUP_CONCAT

答案 2 :(得分:1)

你可以尝试这样的东西:

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

试用here效果很好!

答案 3 :(得分:0)

不确定您将拥有多少组,但如果它是有限数字,我建议您为每个组创建一个列或使用mysql data type SET(位屏蔽)。

答案 4 :(得分:0)

我不确定这是否是你做事的方式(因为我在这里很新),但如果这是你正在使用的例子,那么让列用户,IN_A,IN_B和IN_C?特别是从那以后你就不会再重复用户数据了