在我的数据库中,我试图为每个制造商找到价格最高的型号。我想进行查询,以便我的输出列出制造商、型号和价格。截至目前,我能够获得制造商的输出和价格,但我不确定如何才能让我的模型显示在结果中。
这是我的代码和当前输出:
Select Product.Maker, Max(U.price)
From (SELECT Price price, Model model
From Desktop
UNION ALL
SELECT Price price, Model model
From Laptop
UNION ALL
SELECT Price price, Model model
From Printer) as U
INNER JOIN Product
ON Product.Model = U.model
GROUP BY Product.Maker
输出:
Maker Max(U.price)
A 899
B 1099
C 1399
D 1699
E 1599
F 1799
G 1899
H 80
I 259
我希望此输出在制造商和价格旁边显示型号,例如:
Maker Price Model
x y z
这是数据库架构,希望对您有所帮助!任何帮助将不胜感激。
Computer Database schemas:
Product( maker, model, type)
Desktop( model, speed, ram, hd, price)
Laptop( model, speed, ram, hd, screen,price)
Printer( model, color, type, price)
如果这也有帮助,我将能够发布所有信息的表格。
最佳答案
你走的很好。您只需要提取每个 Maker 的第一行。用group_concat您可以将模型列汇总为每个制造商的逗号分隔字符串,按其价格排序:
group_concat(Model order by Price desc)
这将为您提供所有型号,首先是价格最高的型号。 然后,使用 substring_index — 抓取逗号前的第一个单词 — 您只能提取第一个模型。
select
Maker,
substring_index(
group_concat(Model order by Price desc), ',',1) model,
max(Price) Price
from (
Select Product.Maker Maker, Product.Model Model, Max(U.price) Price
From (SELECT Price price, Model model
From Desktop
UNION ALL
SELECT Price price, Model model
From Laptop
UNION ALL
SELECT Price price, Model model
From Printer) as U
INNER JOIN Product ON Product.Model = U.model
GROUP BY Product.Maker, Product.Model
) t
group by Maker
请参阅此页面了解概念解释:Selecting Only One Row Per Group
关于mysql - 使用 UNION 进行 3 种不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42655407/