同一列上有多个“和”

时间:2015-04-15 20:12:20

标签: sql-server

我想知道如何在SQL查询中使用多个ands。所以在下面的例子中(有效)。

select distinct 
    Room_Facilities.Room_ID 
from 
    [Room_Facilities] 
inner join 
    [Rooms] on Room_Facilities.Room_ID = Rooms.Room_ID
where 
    Building_ID = 'LDS' 
    and Room_Facilities.Facility_ID  = 'C'

我想添加另一个'和'所以选择的房间有设施' C'以及' V'。我试过这个,然后它返回null。目前,它只适用于Facility_ID的一个和条件,但我想要多个(在下面的示例中有2个,它不起作用,仅适用于1)。

select distinct 
    Room_Facilities.Room_ID 
from 
    [Room_Facilities] 
inner join 
    [Rooms] on Room_Facilities.Room_ID = Rooms.Room_ID
where 
    Building_ID = 'LDS' 
    and Room_Facilities.Facility_ID = 'C' 
    and Room_Facilities.Facility_ID = 'V'

5 个答案:

答案 0 :(得分:6)

您需要加入Room_Facilities表中的两条记录,例如:

select distinct 
    room.Room_ID 
from 
    [Rooms] room
    join [Room_Facilities] facility1 ON room.Room_ID = facility1.Room_ID
    join [Room_Facilities] facility2 ON room.Room_ID = facility2.Room_ID
where 
    room.Building_ID = 'LDS' 
    and facility1.Facility_ID = 'C' 
    and facility2.Facility_ID = 'V'

这是因为任何Facility_ID都不能等于'C'且等于'V',但Rooms表中的记录可以被引用Room_Facilities中的多个记录。这就是为什么它们存储在不同的表中,Room_Facilities引用Room_ID({I}},它(我假设)唯一地确定Rooms中的条目。人们将此称为one-to-many relationship

(旁注,人们通常不会用多个名字命名表格)

答案 1 :(得分:5)

您想使用IN

select distinct Room_Facilities.Room_ID from [Room_Facilities] inner join [Rooms]
on Room_Facilities.Room_ID = Rooms.Room_ID
where Building_ID = 'LDS' and 
Room_Facilities.Facility_ID  IN ('C','V')

编辑:Here's a sample Fiddle,未授予您的确切架构。

答案 2 :(得分:2)

加入的一些替代方案是GROUP BY

SELECT RF.Room_ID
FROM   [Room_Facilities] RF
       INNER JOIN [Rooms] R
         ON RF.Room_ID = R.Room_ID
WHERE  R.Building_ID = 'LDS'
       AND RF.Facility_ID IN ( 'C', 'V' )
GROUP  BY RF.Room_ID
HAVING COUNT(DISTINCT RF.Facility_ID) = 2; 

INTERSECT

SELECT Room_ID
FROM   [Rooms]
WHERE  Building_ID = 'LDS'
INTERSECT
SELECT Room_ID
FROM   [Room_Facilities]
WHERE  Facility_ID = 'C'
INTERSECT
SELECT Room_ID
FROM   [Room_Facilities]
WHERE  Facility_ID = 'V' 

答案 3 :(得分:0)

你想要OR,因为它不能是两个值。然后将那些带有parens的组合起来以保持AND正常工作。

select distinct Room_Facilities.Room_ID from [Room_Facilities] inner join [Rooms]
on Room_Facilities.Room_ID = Rooms.Room_ID
where Building_ID = 'LDS' and 
 (Room_Facilities.Facility_ID  = 'C' OR Room_Facilities.Facility_ID = 'V')

答案 4 :(得分:0)

必须记住,AND查询中的SQL条件实际上并不适用于人类倾向于思考的语句。 SQL以行为基础评估条件,因此在您的情况下,您不能在一行中有两个不同的值 - 对吗?

我的意思是在一行中,您Facility_ID'C'都不能'V'

您要执行的操作是使用IN运算符来列出此列可能包含的值,以使其符合您的WHERE条件。

完成
WHERE Building_ID = 'LDS' AND Facility_ID IN ('C', 'V')

或者您也可以使用OR - 这实际上是一个更长的版本(通过代码中的字符)但在性能方面不是必需的 - 数据库必须转换上面的查询(参见{{1}有关细节)。代码看起来像

EXPLAIN

请记住括号,因为您要检索WHERE Building_ID = 'LDS' AND ( Facility_ID = 'C' OR Facility_ID = 'V' ) 的行Building_ID = 'LDS'和值'C' or 'V'之一。

修改

我可能误解了这个问题,假设您要列出所有设施Facility_IDC的房间。如果您需要两个工具,则必须使用相同的条件V两次使用相同的条件并对这些表进行别名,然后在JOIN子句中放置

WHERE

重要提示我会考虑与可以存储每个房间设施的表格建立一对多的关系。