SQL:仅查询在与其关联的第二个表中具有两行的结果

时间:2012-07-12 16:18:31

标签: mysql sql

我对SQL比较新,所以以下可能是一个简单的问题。我一直在尝试编写一个只返回具有两个特定类型地址的名称的查询。有一个名称表和一个地址表。它在MYSQL服务器中。

    customer
| id |  name       |
|  1 | john smith  |
|  2 | bob vance   |
|  3 | jane doe    |
|  4 | doug smith  |


                           address
| id |    type   |      street      |   state   |  name_id  |
|  1 |    home   | 123 main street  |     NJ    |     3     |
|  2 |  business | 100 south lane   |     NY    |     3     |
|  3 |    home   | 75 boardwalk way |     CT    |     1     |
|  4 |    home   |  3 cherry lane   |     NY    |     2     |
|  5 |    home   |   15 south way   |     NY    |     4     |
|  6 |  business |   90 west end    |     NY    |     4     |

我想返回同时拥有家庭和公司地址的姓名,在下面的结果中进行了演示。

| name     |  type        |    street       |   state   |
| jane doe |    home      | 123 main street |     NJ    |
| jane doe |   business   | 100 south lane  |     NY    |
|doug smith|   home       |  15 south way   |     NY    |
|doug smith|  business    |  90 west end    |     NY    |

我可以将这些表连接在一起,但是我很难以这种方式进行过滤。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:5)

SELECT ...
FROM ...
WHERE name_id IN (SELECT name_id
                  FROM address
                  WHERE type IN ('home', 'business')
                  GROUP BY name_id
                  HAVING COUNT(DISTINCT(type)) = 2)

http://sqlfiddle.com/#!2/be63a/1