MySQL:获取所有具有一年id但不具有另一年id的记录
我有一张桌子:MySQL:获取所有具有一年id但不具有另一年id的记录,sql,mysql,Sql,Mysql,我有一张桌子: HOST_ID | ContractYear 1 | 2008 2 | 2008 3 | 2008 1 | 2009 4 | 2009 我需要的是一个查询,它将告诉我2009年的所有主机ID,而不是2008年的主机ID 上面示例中的答案是HOST_ID=4 谢谢。使用: select HOST_ID from table_name where ContractYear = 2009 AND HOST_I
HOST_ID | ContractYear
1 | 2008
2 | 2008
3 | 2008
1 | 2009
4 | 2009
我需要的是一个查询,它将告诉我2009年的所有主机ID,而不是2008年的主机ID
上面示例中的答案是HOST_ID=4
谢谢。使用:
select
HOST_ID
from
table_name
where
ContractYear = 2009
AND HOST_ID NOT IN (select HOST_ID from table_name where ContractYear = 2008)
使用:
更通用,因为它过滤掉了所有不是你要找的年份
select HOST_ID
from table t
where ContractYear = 2009
and HOST_ID not in (select distinct HOST_ID
from table t2
where t.ContractYear != t2.ContractYear)
更通用,因为它过滤掉了所有不是你要找的年份
select HOST_ID
from table t
where ContractYear = 2009
and HOST_ID not in (select distinct HOST_ID
from table t2
where t.ContractYear != t2.ContractYear)
+1:这应该比使用NOT EXISTS快,请参阅:+1:这应该比使用NOT EXISTS快,请参阅:这与mediaslave要求的略有不同。这将选择所有主机ID,其中ContractYear为2009,并且主机ID以前从未出现在t2中。这与mediaslave要求的略有不同。这将选择所有主机ID,其中ContractYear为2009,并且主机ID以前从未出现在t2中。
select HOST_ID
from table t
where ContractYear = 2009
and HOST_ID not in (select distinct HOST_ID
from table t2
where t.ContractYear != t2.ContractYear)