在SQL Server中使用AND命令不给出预期的结果

时间:2014-04-10 12:16:32

标签: sql

我正在尝试编写一些代码来确定在执行其他代码之前,另一个表中是否存在1个表中的2个值。我找到了这些:

select count(1)
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Home Team');

select count(1)
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Away Team');
当表Team Team TeamName中存在值时,

都会按预期返回值1。但是,这个:

select count(1)
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Home Team')
AND TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Away Team');

当(据我所见)它应该结合前两个查询并返回1时返回0。 谁能告诉我我做错了什么?

2 个答案:

答案 0 :(得分:4)

我认为这种方式更具可读性:

select count(1)
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header in ('Home Team', 'Away Team'))

返回1的方法是解码结果:

select case when count(1) = 0 then 0 else 1 end
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header in ('Home Team', 'Away Team'))

答案 1 :(得分:2)

您当前的查询说的是:计算TeamName为Home AND Away team的所有行。 将AND替换为OR:一个团队可以是家庭团队或远程团队:

select count(1)
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Home Team')
OR TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Away Team');

编辑:快速而又肮脏的方式只返回1:

select CASE WHEN count(1) > 0 THEN 1 ELSE 0 END
from Team
where TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Home Team')
OR TeamName IN (select Data FROM CSVTest_Match WHERE Header = 'Away Team');