简体   繁体   English

选择多对多关系中的所有唯一可能(多个)值?

[英]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; 我想要的是一个SQL查询,以从多对多关系中返回所有可能的值; 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). 感谢@jarlh提出使用组concat的建议(不知道此类功能)。

The solution in this case (and for MySQL) would be: 在这种情况下(对于MySQL)的解决方案是:

select distinct group_concat(preferred_color)
  from my_table
  group by person_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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