关系:
Product(maker, model, type)
Laptop(Model, price, speed, ram, hd, screen)
PC(model, price, speed, ram, hd)
Printer(model,price, color, price)
我正在尝试找到价格最高的产品型号。
我尝试过:
-> SELECT model, MAX(price) FROM
-> ((SELECT model, MAX(price) FROM product NATURAL JOIN pc)
-> union
-> (SELECT model, MAX(price) FROM product NATURAL JOIN printer)
-> union
-> (SELECT model, MAX(price) FROM product NATURAL JOIN laptop));
我一直得到的错误是“错误1054(42S22):'字段列表'中的未知列'价格'”
答案 0 :(得分:0)
您需要在子选择中对max()函数进行别名:
SELECT model, MAX(price)
FROM (
SELECT model, MAX(price) AS price ...
^^^^^^^^^
etc...
你基本上是用子查询动态创建一个表,所以外部查询必须是
SELECT model, MAX(MAX(price))
^^^^^^^^^^--- field name in subselects
这不会真正起作用。你正在对字段名称(价格)进行双MAX()调用,而不是从子查询返回。
答案 1 :(得分:0)
该查询无效。鉴于您的询问,我认为这是您正在寻找的东西:
(SELECT model, price FROM product NATURAL JOIN pc)
union all
(SELECT model, price FROM product NATURAL JOIN printer)
union all
(SELECT model, price FROM product NATURAL JOIN laptop)
ORDER BY price DESC
LIMIT 1
修改:根据您的评论扩展答案
好吧,之前的查询导致一个元组。如果你只是一个字段/属性/列,那么你应该这样做:
SELECT model from (
(SELECT model, price FROM product NATURAL JOIN pc)
union all
(SELECT model, price FROM product NATURAL JOIN printer)
union all
(SELECT model, price FROM product NATURAL JOIN laptop)
) final
ORDER BY price DESC
LIMIT 1
但这会慢一点,而且可能是不必要的。
我没有得到where price < all
。如果您通过价格desc订购并且只获得第一条记录,您将只获得最高价格的记录。