MySQL从关联表中选择具有相同亲戚的地方

时间:2018-12-12 07:50:57

标签: mysql

我遇到这样的关系表:

eaters:

id   name     fruit
1    jack     banana
2    jack     apple
3    jane     banana
4    jane     apple
5    jane     orange
6    richard  banana
7    richard  apple

现在,谁吃了与“杰克”相同类型的水果?

例如,在上表中,“理查德”就是答案。

我想到的伪查询是:

SELECT name AS the_guy 
FROM eaters 
WHERE 
  (SELECT fruit FROM eaters WHERE name=the_guy) = 
  (SELECT fruit FROM eaters WHERE name='jack')

我不知道在MySQL中这是否可能。现在,我使用PHP提取了整个表并从结果中提取答案,这不是一个好方法。有什么建议吗?

4 个答案:

答案 0 :(得分:3)

您可以写:

SELECT e2.name
FROM   eaters e1
      INNER JOIN eaters e2
              ON e1.fruit = e2.fruit
WHERE  e1.name = 'Jack'
      AND e2.name != 'Jack'
GROUP  BY e2.name 

答案 1 :(得分:2)

这很容易理解:

SELECT DISTINCT name FROM eaters 
WHERE
    name <> 'Jack' 
    AND 
    fruit IN (SELECT fruit FROM eaters WHERE name = 'Jack')

答案 2 :(得分:1)

一种方法可以是将条件Group_Concat()Having子句一起使用。我们可以在子查询(派生表)中的逗号分隔的字符串中获得jack的所有结果。

现在,我们可以获得与其他人相同的水果排序列表,并使用HAVING子句考虑与{jack_fruits“相匹配的name值。

查询

SELECT t1.name AS the_guy 
FROM eaters AS t1 
JOIN (SELECT GROUP_CONCAT(fruit ORDER BY fruit) AS jack_fruits
      FROM eaters 
      WHERE name = 'jack') AS t2 
WHERE t1.name <> 'jack' 
GROUP BY t1.name 
HAVING GROUP_CONCAT(t1.fruit ORDER BY fruit) = MAX(t2.jack_fruits );

结果

| the_guy |
| ------- |
| richard |

View on DB Fiddle

答案 3 :(得分:1)

最好使用这个:

SELECT DISTINCT
       e.name
FROM eaters e
WHERE name <> 'jack'
      AND NOT EXISTS
(
    SELECT DISTINCT
           name
    FROM eaters e1
    WHERE NOT EXISTS
    (
        SELECT * FROM eaters e2 WHERE e2.name = 'jack' AND e1.fruit = e2.fruit
    )
          AND e1.name = e.name
);