Group on an equal footing

Asked

Viewed 105 times

3

I need to group the result when there are equal records, regardless of the order, whenever the same colors are chosen - group the colors and the users. I need to produce an output like the one below:

0 => array( 'cores' => 'azul, verde' , 'user' => '1, 3' )
1 => array( 'cores' => 'azul'        , 'user' => '2' )

// Usuarios 1 e 3 escolheram azul e verde
// Usuario 2 escolheu azul

My table

TABELA.ESCOLHA    TABELA.CORES
ID | USER         ID | ESCOLHA | CORES
---------         ---------------------
 1 | 1             1 | 1       | azul
 2 | 2             2 | 1       | verde
 3 | 3             3 | 2       | azul
                   4 | 3       | azul
                   5 | 3       | verde

My query

select
    group_concat( user  ) user
  , group_concat( cores ) cores
from escolha
inner join cores
        on cores.escolha = escolha.id
  group by user

I tried to group by user, tried with other fields, but did not work as expected.

  • Your query did not produce the result you wanted? See: http://sqlfiddle.com/#! 2/587a3/1

  • @vmartins, did not produce, because I wanted to group user 1 with user 3 because they are equal, and the result would be an array with 2 values: 1 => 'user 1, user 3' , 2 => 'user 2'

1 answer

2


SELECT
  group_concat(user) user,
  cores
FROM (
  SELECT
      user,
      group_concat(cores ORDER BY cores ASC) cores
  FROM
      escolha
  INNER JOIN cores ON cores.escolha = escolha.id
  GROUP BY
      user
) tmp
GROUP BY cores

http://sqlfiddle.com/#! 2/519ed/8/0

  • That’s almost it. I include for user 2 the colors yellow, blue, and it grouped only by user, and in case should be 2 lines( user 2: yellow and user 2: blue). I believe changing the GROUP BY resolve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.