SQL查询EXCEPT

时间:2013-03-12 03:03:36

标签: mysql sql group-by

如果我的表设置如下:

╔══════╦══════╗
║  A   ║  B   ║
╠══════╬══════╣
║ Sam  ║ sec2 ║
║ Sam  ║ sec2 ║
║ Sam  ║ sec2 ║
║ Fred ║ sec1 ║
║ Fred ║ sec2 ║
║ Fred ║ sec1 ║
║ Joe  ║ sec1 ║
║ Joe  ║ sec1 ║
╚══════╩══════╝

我希望结果是

╔═════╦══════╗
║  A  ║  B   ║
╠═════╬══════╣
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Joe ║ sec1 ║
║ Joe ║ sec1 ║
╚═════╩══════╝

所以基本上我想查询sec1或sec2但不是两者的人,我想留下重复项。

我的尝试:

SELECT A, B
FROM TABLE
WHERE (A = 'SAM' OR A = 'FRED' OR A = 'JOE') AND NOT (B = 'sec1' AND B = 'sec2')

1 个答案:

答案 0 :(得分:3)

好的,如果表上还有其他列,则此查询很有用。子查询的作用是单独获取仅A唯一的BMAX(B) = MIN(B)COUNT(DISTINCT B) = 1相同。然后,通过列A将子查询的结果连接回表本身。

SELECT  y.*
FROM    tableName y
        INNER JOIN
        (
            SELECT  A
            FROM    tableName
            GROUP   BY A
            HAVING  MAX(B) = MIN(B) 
                    AND MAX(B) IN ('sec1', 'sec2')
        ) x ON y.A = x.A

OR

SELECT  y.*
FROM    tableName y
        INNER JOIN
        (
            SELECT  A
            FROM    tableName
            GROUP   BY A
            HAVING  COUNT(DISTINCT B) = 1 
                    AND MAX(B) IN ('sec1', 'sec2')
        ) x ON y.A = x.A