sql查询为所有或没有条件选择匹配的行

时间:2014-05-21 04:46:11

标签: sql sql-server-2005

我有一张车牌,每辆车都属于一家公司。在另一张表格中,我列出了按城市划分的公司位置列表。

我想从汽车表中选择所有公司在所有城市都有位置的汽车进入存储过程,否则即使它们不在一个城市,也要将这些汽车全部排除在外。

所以,我尝试过类似的事情:

select id, cartype from cars where companyid in 
(
  select id from locations where cityid in 
  (
     select id from cities
  )
)

这不起作用,因为它显然满足条件,如果任何城市都在列表中,而不是所有城市。

这听起来像一群人,但不能使它与我尝试的一起工作。

我正在使用MS SQL 2005

3 个答案:

答案 0 :(得分:2)

一个例子:

select id, cartype from cars c
where ( select count(1) from cities where id in (...))
    = ( select count(distinct cityid)
        from locations 
        where c.companyid = locations.id and cityid in (...) )

答案 1 :(得分:0)

也许尝试计算所有城市,然后选择汽车,如果公司有相同数量的不同位置城市,那么总城市。

SELECT id, cartype FROM cars
WHERE
    --Subquery to find the number of locations belonging to car's company
    (SELECT count(distinct cities.id) FROM cities
    INNER JOIN locations on locations.cityid = cities.id
    WHERE locations.companyId = cars.companyId)
    =
    --Subquery to find the total number of locations
    (SELECT count(distinct cities.id) FROM cities)

我还没有对此进行测试,它可能不是最有效的查询,但我认为这可能会有效。

答案 2 :(得分:0)

试试这个

SELECT e.* 
FROM cars e
WHERE NOT EXISTS (
    SELECT 1 
    FROM Cities p
    WHERE p.location = e.Location
)