2013-12-13 92 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。 。 。谢谢。 –