-3

假设我有一桌人,一桌水果和一桌喜欢。

People              fruit               likes
+-----+--------+    +-----+---------+   +-----+-----+
| pid | people |    | fid |  name   |   | pid | fid |
+-----+--------+    +-----+---------+   +-----+-----+
|  1  | Mary   |    |  1  | appple  |   |  1  |  1  |
|  2  | Tom    |    |  2  | orange  |   |  2  |  1  |
|  3  | John   |    |  3  | banana  |   |  2  |  2  |
|  4  | George |    |  4  | coconut |   |  2  |  3  |
...

我想做一个查询,可以搜索喜欢苹果和橙子的人:

Result
+----------+---------------
| People   |  likes
+----------+---------------
| Tom      | apple, orange, banana

其实我也想知道how to make the same output above but with different conditions说喜欢橘子不喜欢苹果的人,或者不喜欢香蕉的人等等。

4

2 回答 2

1
SELECT   people
FROM     People
    JOIN likes USING (pid)
    JOIN fruit USING (fid)
GROUP BY pid

然后:

  1. 喜欢苹果和橙子的人

    HAVING   SUM(name='apple') AND SUM(name='orange')
    
  2. 喜欢橙色但不喜欢苹果的人

    HAVING   SUM(name='orange') AND NOT SUM(name='apple')
    
  3. 喜欢橙色但不喜欢苹果的人

    HAVING   NOT SUM(name='banana')
    

在sqlfiddle上查看它们。

于 2013-07-16T11:55:00.683 回答
0
SELECT p.people, GROUP_CONCAT(DISTINCT f.name)
FROM people p INNER JOIN likes l ON p.pid = l.pid
    INNER JOIN fruit f ON l.fid = f.fid
WHERE p.id = 2
GROUP BY p.people
于 2013-07-16T11:55:49.690 回答