我有下表;
user | column2 |
--------+------------+
tom | Created |
test | Created |
fred | Removed |
tom | Removed |
fred | Created |
holly | Created |
test | Modified |
我希望查询该表以返回具有CREATED且没有具有REMOVED值的用户的用户。此外,具有MODIFIED的用户可以显示,但不能显示具有MODIFIED值的行。
结果应该是:
user | column2 |
-------+------------+
test | Created |
Holly | Created |
我只使用WHERE子句,还有另一种方法可以实现吗?
非常感谢任何给出的建议
答案 0 :(得分:2)
使用NOT EXISTS
:
SELECT user, column2
FROM mytable AS t1
WHERE column2 = 'Created' AND
NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.user = t2.user AND t2.column2 = 'Removed')
答案 1 :(得分:2)
您可以使用LEFT JOIN
来完成SELECT t.user,t.column2
FROM YourTable t
LEFT OUTER JOIN YourTable s
ON(t.user = s.user and s.column2 = 'Removed')
WHERE s.user is null
and t.column2 ='Created'
答案 2 :(得分:0)
另一种方法,做一个GROUP BY
。让HAVING
子句检查用户的最小值是否已创建。
select user, min(column2)
from tablename
group by user
having min(column2) = 'Created'
and max(column2) < 'Removed'