MySQL查询匹配两个字段并具有另一个共同字段

时间:2011-10-17 18:10:04

标签: mysql sql

我有一个这样的SQL表:

id |  f1 | f2
 1 |  a  | hi
 2 |  a  | sup
 3 |  b  | hi

我需要一个查询来抓取f2 = hi OR f2 = sup的行,但前提是f1在两行中都有相同的值。所以我的查询会抓住id 1和id 2,但不是3

所以基本上这个 -

SELECT * FROM `table` WHERE (`f2` = 'hi' OR `f2` = 'sup') AND 'f1-is-the-same'

3 个答案:

答案 0 :(得分:2)

SELECT *
    FROM YourTable t1
        INNER JOIN YourTable t2
            ON t1.f1 = t2.f1
    WHERE t1.f2 = 'hi'
        AND t2.f2 = 'sup'

答案 1 :(得分:1)

SELECT * FROM `table` as t1 
WHERE (`f2` = 'hi' OR `f2` = 'sup') 
  AND f1 in (select f1 from `table` where id <> t1.id)

答案 2 :(得分:0)

像这样的查询应该可以解决问题

SELECT T1.id,T1.F1,T2.F2
FROM Table as T1
INNER JOIN Table as T2 
ON T1.F1=T2.F1 AND T1.ID <> T2.ID
WHERE T1.F2= 'hi' or T1.F1='sup'