2

我对 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    |

我可以将表格连接在一起,但是我很难以这种方式过滤。任何帮助将不胜感激!

4

1 回答 1

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

于 2012-07-12T16:21:32.977 回答