从表1中选择与表2中的2条记录匹配的记录

时间:2018-08-19 16:37:15

标签: mysql

我有以下情况。

表1

+----+-------------+
| id | name        |
+----+-------------+
|  1 | John        |
|  2 | Alice       |
+----+-------------+

表2

+----+--------------+--------------+
| id | trait        | color        |
+----+--------------+--------------+
|  1 | hair         | blond        |
|  1 | eyes         | blue         |
|  2 | hair         | brown        |
|  2 | eyes         | blue         |
+----+--------------+--------------+

我想在一个查询中找到每个金发碧眼的人的名字。我已经尝试过类似的方法,但是没有用:

SELECT t1.name FROM table1 as t1, table2 as t2
    WHERE
        t1.id = t2.id AND
        (t2.trait = 'hair' and t2.trait = 'blond') AND
        (t2.trait = 'eyes' and t2.trait = 'blue');

我当然正在寻找实现此目的的最有效的MySQL方法。

编辑:最初的问题太简单了,不能准确反映我的情况

2 个答案:

答案 0 :(得分:1)

首先,您要构建一个JOIN,将人与特质结合起来。

SELECT
    p.id,
    p.name,
    t.trait,
    t.color
FROM
    person p
JOIN
    trait t ON p.id = t.userId;
+----+-------+-------+-------+
| id | name  | trait | color |
+----+-------+-------+-------+
|  1 | John  | hair  | blond |
|  1 | John  | eyes  | blue  |
|  2 | Alice | hair  | brown |
|  2 | Alice | eyes  | blue  |
+----+-------+-------+-------+

您可以根据需要的特征对其进行过滤:

SELECT
    p.id,
    p.name,
    t.trait,
    t.color
FROM
    person 
JOIN
    trait t ON p.id = t.userId
WHERE
    (t.trait = 'hair' AND t.color = 'blond') OR
    (t.trait = 'eyes' AND t.color = 'blue');
+----+-------+-------+-------+
| id | name  | trait | color |
+----+-------+-------+-------+
|  1 | John  | hair  | blond |
|  1 | John  | eyes  | blue  |
|  2 | Alice | eyes  | blue  |
+----+-------+-------+-------+

然后按人员将它们分组,以计算一个人要寻找的特征中有多少特征:

SELECT
    p.id,
    p.name,
    COUNT(*) AS numTraits
FROM
    person p
JOIN
    trait t ON p.id = t.userId
WHERE
    (t.trait = 'hair' AND t.color = 'blond') OR
    (t.trait = 'eyes' AND t.color = 'blue')
GROUP
    BY p.id, p.name;
+----+-------+-----------+
| id | name  | numTraits |
+----+-------+-----------+
|  1 | John  |         2 |
|  2 | Alice |         1 |
+----+-------+-----------+

然后仅选择具有所需数量特征的人员:

SELECT
    p.id,
    p.name,
    COUNT(*) AS numTraits
FROM
    person p
JOIN
    trait t ON p.id = t.userId
WHERE
    (t.trait = 'hair' AND t.color = 'blond') OR
    (t.trait = 'eyes' AND t.color = 'blue')
GROUP BY
    p.id, p.name
HAVING
    numTraits = 2;
+----+------+-----------+
| id | name | numTraits |
+----+------+-----------+
|  1 | John |         2 |
+----+------+-----------+

答案 1 :(得分:1)

我认为您需要在join中进行两次Table2,一个是头发,另一个是眼睛。

SELECT
   t1.id,t1.name
FROM
    Table1 t1 
    JOIN Table2 hair ON t1.id = hair.id and hair.trait = 'hair'
    JOIN Table2 eyes ON t1.id = eyes.id and eyes.trait = 'eyes'
WHERE
    (hair.color = 'blond')
AND
    (eyes.color = 'blue')

sqlfiddle

[结果]

| id | name |
|----|------|
|  1 | John |