gpt4 book ai didi

mysql - 在数据库中使用子查询是更好的做法吗?

转载 作者:行者123 更新时间:2023-11-29 06:25:47 24 4
gpt4 key购买 nike

考虑具有以下模式的两个表

Raipur_Restaurant_List

RestID
name

其中 RestID 是主键

Raipur_Restaurant_List_Dine_Types

RestID
Dine_Name

其中 RestID 是引用 Raipur_Restaurant_List 表的外键

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 的聚合组,因为这意味着它必须具有两个值:

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() 子句本身将返回只有 HomeDelivery,Bakeries 中的一个或另一个的行。通过应用 COUNT(),您可以确保只返回匹配两者的那些。

如果您需要添加额外的匹配项,请将它们添加到 IN () 列表中,并在 HAVING 子句中增加要比较的数字,使其与IN () 列表的长度。

COUNT() 中的 DISTINCT 关键字只有在 same Dine_Name 有可能时才需要每个 RestID 存在不止一次。如果 RRLDT 中永远不会有重复的 RestID, Dine_Name 对,则那里不需要 DISTINCT

Here is a demonstration...

关于mysql - 在数据库中使用子查询是更好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31079578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com