SQL:你如何加入为你提供INVERSE行?

时间:2013-07-12 21:45:15

标签: sql join

我有一个看起来像的查询:

SELECT b.user_name FROM
(SELECT user_name FROM my_table_name
WHERE date='2013-07-11') a
JOIN
(SELECT user_name FROM my_table_name
WHERE date='2013-06-11') b
ON 
a.user_name != b.user_name

如何在6月份为我提供姓名,而不是7月份?

1 个答案:

答案 0 :(得分:2)

这称为反连接。如果您的RDBMS支持,可以使用SQL标准EXCEPT运算符。

SELECT user_name
FROM   my_table_name
WHERE  date = '2013-06-11'
EXCEPT
SELECT user_name
FROM   my_table_name
WHERE  date = '2013-07-11' 

其他可能性包括NOT INNOT EXISTSLEFT OUTER JOIN ... NULL,或者您可以使用GROUP BY,如下所示。

SELECT user_name
FROM   my_table_name
WHERE  date IN ('2013-06-11', '2013-07-11')
GROUP BY user_name
HAVING MAX(date) = '2013-06-11'