2
我的数据库看起来是这样的:复杂的SQL查询
Customer (c_id, c_name)
Products (p_id, p_name, p_cost)
Buys (p_id references Products, c_id references Customer)
我想查询以下数据库:
- 客户w^ith最大产品数量:如果有2个或更多客户有相同数量的产品,那么将考虑所有产品的总价格
我试过了,但它显示错误消息:“语法不正确附近)“。
我想调试它没有收获。
任何人都可以调试此查询,甚至建议一个更优化的查询?
select a1.c_id, a1.c_name
from
(select c.c_id, c.c_name
from Customer c
where c.c_id in
(select b.c_id
from Buys b
group by b.c_id
having COUNT(b.p_id) >= all
(
select COUNT(b.p_id)
from Buys b
group by b.c_id
)
)
)
as a1
join
(select b.c_id, SUM(p.p_cost) as 'SumCost'
from Buys b
join Products p on b.p_id = p.p_id
group by b.c_id
) as a2 on a1.c_id = a2.c_id
where
a2.SumCost = (select MAX(SumCost)
from
(select b.c_id, SUM(p.p_cost) as 'SumCost'
from Buys b
join Products p on b.p_id = p.p_id
group by b.c_id
)
)
更新:
上面的查询是由mohdowais成功调试。 我现在认为这个查询效率不高。你们都可以请建议一个更有效的吗? 我没有使用任何索引。
@米奇小麦:谢谢。有效。但我需要更多地了解它。你能否详细说明一下“maxTmp”? – Kameron
当从选择结果中选择时,必须给选择结果一个别名:'select * from(select * from blah)someAlias' – Bohemian
@米奇小麦:谢谢.... – Kameron