我想知道如何在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'
答案 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_ID
或C
的房间。如果您需要两个工具,则必须使用相同的条件V
两次使用相同的条件并对这些表进行别名,然后在JOIN
子句中放置
WHERE
重要提示我会考虑与可以存储每个房间设施的表格建立一对多的关系。