假设这些是数据库中的三个表和各自的列。
获取每家商店销售额最高的食谱的查询是什么?
我使用了这个查询,但它显示了一半的结果。
select distinct Store_Location, Recipe, No_of_Orders
from [ORDER]
join PERSON on [ORDER].Email_ID = PERSON.Email_ID
join ADDRESS on PERSON.Address = ADDRESS.Address
答案 0 :(得分:2)
像这样:
Bool
此查询的工作原理是将原始查询的行与返回当前行存储的最大select distinct Store_Location, Recipe, No_of_Orders
from [ORDER] As o
join PERSON As p on o.Email_ID = p.Email_ID
join ADDRESS As a on p.Address = a.Address
WHERE No_of_Orders = (
select MAX(o2.No_of_Orders)
from [ORDER] As o2
join PERSON As p2 on o2.Email_ID = p2.Email_ID
join ADDRESS As a2 on p2.Address = a2.Address
Where a2.Address = a.Address
)
的子查询进行比较。如果它们匹配,那么这必须是" 该商店销售额最高的食谱",所以我们保留它,否则我们将它从最终的行集中排除
No_of_Orders
,As o
位被称为"表别名"。它们是为查询中的表的每种不同用法提供本地名称的方法。它们在这里是必要的,因为在子查询中我们重新查询与外部查询中相同的表,我们需要能够区分我们所引用的每个列的含义。