简体   繁体   中英

Select all unique possible (multiple) values in a many-to-many relationship?

Suppose there is a simple table like a many-to-many relationship.

person_id | preferred_color
-------------------
1         | BLUE
1         | RED
2         | BLUE
3         | BLUE
3         | RED
4         | BLUE
5         | BLUE
5         | RED 
5         | GREEN
6         | RED
6         | GREEN

What I would like is an SQL query to return all the possible values from the many-to-many relationship; for the given example all the possible favorite colors for a person : [(BLUE, RED), (BLUE), (BLUE,RED,GREEN), (RED, GREEN)].

Selecting only possibilities of one preferred color is quite easy with a simple select; even with two two preferred color is possible, with a self join. But with a variable number of preferred colors?

Thanks to @jarlh for suggestion to use group concat (wasn't aware of such function).

The solution in this case (and for MySQL) would be:

select distinct group_concat(preferred_color)
  from my_table
  group by person_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM