选择并由多个行值确定

时间:2013-07-16 11:50:31

标签: mysql sql

假设我有一张桌子,桌上的水果和一张桌子。

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说喜欢橙子但不喜欢苹果的人或不喜欢香蕉的人等。

2 个答案:

答案 0 :(得分: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')
    
  4. sqlfiddle上查看。

答案 1 :(得分: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