两行中都存在具有值的返回行

时间:2013-01-23 08:07:12

标签: mysql sql

+------+------+------------+------+
| id   | type| design| location   |
+------+------+------------+------+
|    1 | abc |    A  | Location X |
|    2 | abc |    A  | Location Y |
|    3 | def |    A  | Location X |
+------+------+------------+------+

我有上面的表格。

假设我想获取位置X和Y中存在的类型。它应该返回第1行和第2行。

我应该使用什么SQL?

3 个答案:

答案 0 :(得分:2)

SELECT type
FROM    tableName
WHERE   location IN ('location x','location y')
GROUP   BY type
HAVING  COUNT(*) = 2

或者如果您想拥有所有这些值,请使用JOIn

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
          SELECT  type
          FROM    tableName
          WHERE   location IN ('location x','location y')
          GROUP   BY type
          HAVING  COUNT(*) = 2
        ) b ON a.type = b.type

SOURCE

答案 1 :(得分:0)

SELECT *
FROM table1
WHERE type IN(SELECT type
              FROM table1
              WHERE location IN('location X', 'location y')
              GROUP BY type
              HAVING COUNT(type) = 2
             );

SQL Fiddle Demo

这会给你:

| ID | TYPE | DESIGN |   LOCATION |
-----------------------------------
|  1 |  abc |      A | Location X |
|  2 |  abc |      A | Location Y |

答案 2 :(得分:0)

如果您只需要检索两者中应存在的类型

    select [type] 
    from ur_table 
    where location = 'Location X'
    intersect 
    select [type] 
    from ur_table 
    where location = 'Location Y'

但如果您真的需要来自2行的所有数据,请尝试

    select id,[type],design, location 
    from ur_table L
    where L.[type] in (select [type] from ur_table where location = 'Location X'
                       intersect select [type] from ur_table where location = 'Location Y'
                       )