2010-09-16 47 views
3

說我有這個數據集「CONTAINS」是否有任何MySQL聚合函數?

 
    user | group 
--------+------- 
[email protected] | A 
[email protected] | B 
[email protected] | A 
[email protected] | B 
[email protected] | A 
[email protected] | B 
[email protected] | C 

我想這個轉換成像這樣的表:

 
    user | IN_A | IN_B | IN_C 
--------+-------+-------+------- 
[email protected] | TRUE | TRUE | FALSE 
[email protected] | TRUE | FALSE | FALSE 
[email protected] | FALSE | TRUE | FALSE 
[email protected] | 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 

我想知道是否有更好的方法來知道一個聚合字段是否包含一個值,或者如果這是唯一的方法?

回答

9

正確的方法做到這一點:

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 
+0

精美的作品! – 2016-09-14 22:13:11

0

不知道你會有多少組,但如果它有一個finiate數字,我建議你爲每個組創建一個列或使用mysql data type SET(位掩碼)。

+0

它是有限的 - 我想從一個雙密鑰(用戶/組)系統中的單一密鑰(用戶)系統,讓每個組移到其自己的專欄。 – Nick 2010-09-16 13:23:31

1

我想這是我不知道這是否是你做事情的方式,唯一的辦法就是,GROUP_CONCAT

+0

我發現唯一的另一種方式是'SELECT u.user,u1.group,g2.group FROM users u LEFT JOIN users u1 ON u.user = u1.user AND u1.group =「A」LEFT JOIN users u2 ON u.user = u2.user AND u2.group =「B」GROUP BY u.user;' – Nick 2010-09-16 13:25:12

+0

它不漂亮,但它可以工作 – 2012-04-26 22:03:30

0

(因爲我很新在這裏),但如果這是你使用止跌的例子使列用戶,IN_A,IN_B和IN_C更容易嗎?特別是因爲這樣的話,你就不會再重複的用戶數據

+0

它會 - 這就是我想要達到的:)數據集使用用戶和組作爲雙列PRIMARY KEY。我想要用戶可以使用PRIMARY KEY並將組拆分成列。 – Nick 2010-09-16 13:22:45

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 

Tryed here工作正常!