2013-12-13 91 views
1

我的問題是關於表中記錄的存在。我怎麼能得到一個真正通知如果我正在尋找des或不存在的記錄的結果列表? 我的意思是,我知道我可以檢查什麼與查詢存在像在MYSQL中檢查記錄存在

SELECT field FROM table WHERE unique_field IN (value1, value2) 

這會告訴我那些記錄至極實際存在。但如果我想得到如下結果:

+--------------+-------+ 
| unique_field | exists| 
+--------------+-------+ 
| value1  | 1  | 
| value2  | 0  | 
+--------------+-------+ 

是否可以這樣做?

回答

0

使用EXISTS(),它停止搜索更多行時有一擊,所以你在搜索大表時不會有太多開銷。

SELECT 'value1' AS unique_field, EXISTS(SELECT 1 FROM your_table WHERE unique_field = 'value1') AS 'exists' 
UNION ALL 
SELECT 'value2' AS unique_field, EXISTS(SELECT 1 FROM your_table WHERE unique_field = 'value2') AS 'exists' 
+0

你說的對,mysql中默認的sql模式是「」,但只要沒有設置sql模式「忽略空間」,這仍然有效。不過謝謝你的建議。 – fancyPants

+0

非常感謝,這工作完美。 – user3100000

0

檢查count(*)得到沒有記錄的,如果它returns 0則沒有記錄的表存在

SELECT count(*) FROM table WHERE unique_field IN (value1, value2); 
0

不是像你一樣,你可以希望,但

select '1', exists(select null from t1 where val = 1) 'exists' 
union 
select '2', exists(select null from t1 where val = 2) 

SELECT 
id as unique_field, exists(select null from t1 where val = id) as 'exists' 
FROM (
    SELECT 1 as id 
    union 
    SELECT 2 
    union 
    select 3 
    union 
    select 4 
) q; 

看到SqlFiddle

1

你也可以做到這一點使用一個「參考」表中的值:

select ref.val, 
     (exists (select 1 from table t where t.unique_field = ref.val)) as `exists` 
from (select 'value1' as val union all 
     select 'value2' as val 
    ) ref; 

你也可以短語這是一個left outer join

select ref.val, 
     (t.unique_field is not null) as `exists` 
from (select 'value1' as val union all 
     select 'value2' as val 
    ) ref left outer join 
    table t 
    on t.unique_field = ref.val; 

這工作,因爲現場在table是唯一的(否則,你可能會得到重複的行或需要聚合)。

+0

我喜歡這個,它利用了MySQL處理左連接的事實,它比子查詢處理好得多。 – GarethD

+0

@RaphaëlAlthaus。 。 。謝謝。 –