MySQL selct条目具有来自同一表的多个值

时间:2019-01-10 09:52:19

标签: mysql

我有两个表(如下所示),我想加入它们并从第二个表中选择具有多个值的人。第一个表是所有人及其唯一ID的列表,第二个表是人们最喜欢的颜色的列表。

表A:唯一ID |名称

+-----+-------------+
| uid | name        |
+-----+-------------+
| 321 | Ana         |
| 662 | Nick        |
| 003 | Fred        |
+-----+-------------+

表B .:表ID |唯一ID |颜色ID

+----------+--------+-----------+
|       id | uid    | color_id  |
+----------+--------+-----------+
|        1 | 121    | 1         |
|        2 | 127    | 2         |
|        3 | 003    | 11        |
|        4 | 002    | 11        |
|        5 | 111    | 3         |
|        6 | 044    | 5         |
|        7 | 003    | 5         |
|        8 | 003    | 8         |
+----------+--------+-----------+

因此,我只想选择与所有给定颜色匹配的用户(uid),例如11和8(红色和紫红色)。在这种情况下,它将是用户003 |弗雷德(Fred),并且每场比赛只有1行,而不是多行(针对每个值)。

我尝试使用where color_id IN (x,y,z...),但这会返回任何列表中至少具有一种颜色的人

2 个答案:

答案 0 :(得分:1)

您可以在下面尝试-

select uniqueid, name from tableA a
inner join tableB b on a.uniqueid=b.uid
where color_id in (11,8)
group by uniqueid, name
having count(distinct color_id)=2

答案 1 :(得分:1)

您可以通过以下方式实现自己的愿望

    select distinct tableA.uid, tableA.name tableB.color_id from tableA 
    inner join tableB on tableA.uniqueid=tableB.uid
    group by tableA.uid , tableA.name ,tableB.color_id
    having count(distinct color_id)=2