检查表MySQL中是否存在值

时间:2012-06-18 23:35:52

标签: mysql sql

有没有办法检查表的列中是否存在多个值,即使这些值不在同一行中?

我有这个问题:

select (select country from storage where country = 'Germany' limit 1) as country,
       (select city from storage where city = 'New York City' limit 1) as city,
       (select pet from storage where pet = 'Dog' limit 1) as pet,
       (select profession from storage where profession='owehs9843' limit 1) as profession

此查询可以满足我的需求。如果该值存在于列中,则返回搜索的值,否则返回null。

一种解决方案是执行if语句并在找到时返回1,否则返回0。

但是,我不确定这是检查每列值的正确方法,而不是每行。我希望值存在于某个列的列中,但每列的键值行不需要关联。

1 个答案:

答案 0 :(得分:1)

刚刚在MySql WorkBench(来自Windows)上对此进行了测试,以下查询在找到值时返回1并且如果没有则返回cero(对于每列)。

select if(sum(country = 'Germany') = 0, 0, 1) as country,
       if(sum(city = 'New York City') = 0, 0, 1) as city,
       if(sum(pet = 'Dog') = 0, 0, 1) as pet,
       if(sum(profession = 'owehs9843') = 0, 0, 1) as profession
from storage;