views:

42

answers:

3

Say I have this data set

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

I want to convert this into a table like this:

  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

I've got:

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

What I'm wondering is if there is a better way to known if an aggregated field contains a value, or if this is the only way?

A: 

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).

Dave
It is finite - I am trying to move from a dual-key (user/group) system to a single key (user) system with each group having its own column.
Nick
A: 

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

Faisal Feroz
The only other way I've found is `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
A: 

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

Harold
It would - thats what I'm trying to achieve :) The Data Set uses User and Group as a double-column PRIMARY KEY. I want to may User the PRIMARY KEY and split the Groups into columns.
Nick