在数据库中使用子查询是更好的做法吗?
Is it better practice to use subquery in database?
考虑两个具有以下模式的 tables
Raipur_Restaurant_List
RestID
name
其中 RestID 是 primary key
Raipur_Restaurant_List_Dine_Types
RestID
Dine_Name
其中 RestID 是 foreign key
引用 Raipur_Restaurant_List table
select distinct RRL.RestID, RRL.name
from Raipur_Restaurant_List as RRL
join Raipur_Restaurant_List_Dine_Types as RRLDT
on RRL.RestID = RRLDT.RestID
where RRLDT.Dine_Name = 'HomeDelivery'
and RRL.RestID
IN (select RestID from Raipur_Restaurant_List_Dine_Types where Dine_Name ='Bakeries')
我正在使用上面的查询来查找那些既有送货上门服务又有面包店的餐馆,有没有更好或更有效的方法来完成这项任务??
提前致谢
另一种只使用一个连接而不使用子查询来完成此操作的方法是使用 IN ()
来匹配 both 所需的值,但也实现了聚合 COUNT()
并将结果集限制为具有 COUNT() = 2
的聚合组,因为这意味着它必须具有 both 值:
SELECT DISTINCT
RRL.RestID,
RRL.name
FROM
Raipur_Restaurant_List as RRL
JOIN Raipur_Restaurant_List_Dine_Types as RRLDT
on RRL.RestID = RRLDT.RestID
WHERE
-- Filter for both values
RRLDT.Dine_Name IN ('HomeDelivery', 'Bakeries')
-- GROUP BY is needed to apply the COUNT()
GROUP BY
RRL.RestID,
RRL.name
-- And filter the aggregate groups
-- for those having exactly two, meaning
-- both conditions were matched by the IN ()
HAVING COUNT(DISTINCT RRLDT.Dine_Name) = 2
IN()
子句本身会 return 行除了两者之外只有 HomeDelivery,Bakeries
中的一个或另一个。通过应用 COUNT()
,您可以确保只有匹配两者的那些才被 returned。
如果您需要添加额外的匹配项,请将它们添加到 IN ()
列表中,同时增加 HAVING
子句中要比较的数字,使其与 [= 的长度相同11=]列表。
只有在 same Dine_Name
每个 Dine_Name
存在不止一次的情况下,才需要 COUNT()
=23=]。如果 RRLDT
中永远不会有重复的 RestID, Dine_Name
对,则那里不需要 DISTINCT
。
考虑两个具有以下模式的 tables
Raipur_Restaurant_List
RestID
name
其中 RestID 是 primary key
Raipur_Restaurant_List_Dine_Types
RestID
Dine_Name
其中 RestID 是 foreign key
引用 Raipur_Restaurant_List table
select distinct RRL.RestID, RRL.name
from Raipur_Restaurant_List as RRL
join Raipur_Restaurant_List_Dine_Types as RRLDT
on RRL.RestID = RRLDT.RestID
where RRLDT.Dine_Name = 'HomeDelivery'
and RRL.RestID
IN (select RestID from Raipur_Restaurant_List_Dine_Types where Dine_Name ='Bakeries')
我正在使用上面的查询来查找那些既有送货上门服务又有面包店的餐馆,有没有更好或更有效的方法来完成这项任务??
提前致谢
另一种只使用一个连接而不使用子查询来完成此操作的方法是使用 IN ()
来匹配 both 所需的值,但也实现了聚合 COUNT()
并将结果集限制为具有 COUNT() = 2
的聚合组,因为这意味着它必须具有 both 值:
SELECT DISTINCT
RRL.RestID,
RRL.name
FROM
Raipur_Restaurant_List as RRL
JOIN Raipur_Restaurant_List_Dine_Types as RRLDT
on RRL.RestID = RRLDT.RestID
WHERE
-- Filter for both values
RRLDT.Dine_Name IN ('HomeDelivery', 'Bakeries')
-- GROUP BY is needed to apply the COUNT()
GROUP BY
RRL.RestID,
RRL.name
-- And filter the aggregate groups
-- for those having exactly two, meaning
-- both conditions were matched by the IN ()
HAVING COUNT(DISTINCT RRLDT.Dine_Name) = 2
IN()
子句本身会 return 行除了两者之外只有 HomeDelivery,Bakeries
中的一个或另一个。通过应用 COUNT()
,您可以确保只有匹配两者的那些才被 returned。
如果您需要添加额外的匹配项,请将它们添加到 IN ()
列表中,同时增加 HAVING
子句中要比较的数字,使其与 [= 的长度相同11=]列表。
只有在 same Dine_Name
每个 Dine_Name
存在不止一次的情况下,才需要 COUNT()
=23=]。如果 RRLDT
中永远不会有重复的 RestID, Dine_Name
对,则那里不需要 DISTINCT
。