2009-11-20 39 views

回答

2
select 
    HOST_ID 
from 
    table_name 
where 
    ContractYear = 2009 
    AND HOST_ID NOT IN (select HOST_ID from table_name where ContractYear = 2008) 
+1

+1年:這應該是比使用更快不存在,請參閱:http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/ – 2009-11-20 17:08:52

1

用途:

SELECT t.host_id 
    FROM TABLE t 
WHERE t.contractyear = 2009 
    AND NOT EXISTS(SELECT NULL 
        FROM TABLE t2 
        WHERE t2.host_id = t.host_id 
        AND t.contractyear = 2008) 
1
SELECT DISTINCT host_id 
FROM mytable mo 
WHERE ContractYear = 2009 
     AND NOT EXISTS 
     (
     SELECT NULL 
     FROM mytable mi 
     WHERE mi.host_id = mo.host_id 
       AND ContractYear = 2008 
     ) 
1

更通用的,因爲它過濾出所有不屬於你正在尋找

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) 
+0

這與介質有點不同 要求。這將選擇其中ContractYear是2009年的所有HOST_ID,並且它的HOST_ID在t2之前從未出現過。 – baudtack 2009-11-20 17:20:06

相關問題