使用Max在My SQL中查找最高价格

时间:2017-03-06 05:43:08

标签: mysql sql

我想找到价格最高的彩色打印机制造商?我的输出应该列出制造商,打印机型号和价格。我假设没有两个型号与最高价格挂钩。

我尝试过:select model,type,max(Price) from Printer where color="TRUE" group by model

但它返回两个价格而不是一个。我也不知道如何加入该表以向最高价的制造商展示。

这是我的架构:

Product (maker, model, type)
Desktop (model, speed, ram, hd, price)
Laptop  (model, speed, ram, hd, screen, price)
Printer (model, color, type, price)

Products
Maker   Model   Type
A   1001    desktop
A   1002    desktop
A   1003    desktop
B   1004    desktop
B   1006    desktop
B   3002    printer
B   3004    printer
C   1005    desktop
C   1007    desktop
D   1008    desktop
D   1009    desktop
D   1010    desktop
D   2001    laptop
D   2002    laptop
D   2003    laptop
D   3001    printer
D   3003    printer
E   2004    laptop
E   2008    laptop
F   2005    laptop
G   2006    laptop
G   2007    laptop
H   3005    printer
I   3006    printer

Desktop
Model   Speed   Ram HD  Price
1001    2.5 256 80  595
1002    2.0 256 80  399
1003    3.1 512 120 899
1004    3.1 1024    120 999
1005    3.1 256 100 999
1006    4.5 512 180 1099
1007    4.5 512 200 1399
1008    4.0 512 100 1199
1009    4.5 512 120 1299
1010    3.0 256 60  495

Laptop
Model   Speed   Ram HD  Screen  price
2001    1.8 256 30  12  799
2002    2.2 128 20  14  1499
2003    2.2 512 40  14  1699
2004    2.5 256 40  12  1499
2005    2.5 512 60  15  1799
2006    2.3 256 40  15  999
2007    3.0 1024    80  17  1899
2008    2.3 256 30  14  1599

Printer
Model   Color   Type    price
3001    True    InkJet  175
3002    True    InkJet  150
3003    False   Laser   295
3004    False   Laser   325
3005    False   inkjet  80
3006    False   Laser   259

4 个答案:

答案 0 :(得分:2)

在下面的查询中,我使用子查询在Printer表中查找最高的打印机价格。然后将其与彩色打印一起用作WHERE子句中的要求。

SELECT p1.Maker,
       p2.model,
       p2.type,
       p2.price
FROM Products p1
INNER JOIN Printer p2
    ON p1.model = p2.model
WHERE p2.price = (SELECT MAX(price) FROM Printer WHERE color = "TRUE")

答案 1 :(得分:1)

Use GROUP BY Clause and MAX function

SELECT PT1.model,PT1.type,PT1.price
FROM Printer PT1
JOIN
(
  SELECT model, MAX(price) AS Price
  FROM Printer
  GROUP BY model
) A ON PT1.model = A.model AND PT1.price = A.Price

答案 2 :(得分:0)

要返回单个价格,您可以使用LIMIT

select model, type, max(Price) from Printer where color="TRUE" group by model limit 1.

答案 3 :(得分:0)

SELECT
       p.model,
       p.type,
       p.price
FROM Products p
JOIN Printer 
    USING(model)
WHERE price = (SELECT MAX(price) FROM Printer WHERE color = "TRUE")