sql max函数错误:关键字“ select”附近的语法不正确

时间:2018-06-21 00:49:46

标签: mysql sql

我有下一个sql代码,您可以在下面看到。它可以正常工作,但条件所在的最后一行除外。

    select m.model,m.price from (
    select product.model, pc.price
    from product
    join pc 
    on product.model=pc.model
    union
    select product.model, laptop.price
    from product
    join laptop 
    on product.model=laptop.model
union
    select product.model, printer.price
    from product
    join printer 
    on product.model=printer.model
    ) m
    where m.price = select max(m.price) from m

下一个错误: 关键字“ select”附近的语法不正确。 如果我把最后一行像这样:where m.price = m.price也可以

2 个答案:

答案 0 :(得分:1)

您是按型号追最高价吗?:

select m.model,MAX(m.price) as price from 
(
    select product.model, pc.price
    from product
    join pc 
    on product.model=pc.model
    union
    select product.model, laptop.price
    from product
    join laptop 
    on product.model=laptop.model
union
    select product.model, printer.price
    from product
    join printer 
    on product.model=printer.model
    ) m
GROUP BY m.model

答案 1 :(得分:1)

如果您正在寻找价格最高的型号:

select m.model, m.price
from (select p.model, pc.price
      from product p join
           pc 
           on p.model = pc.model
      union all
      select p.model, laptop.price
      from product join
           laptop 
           on p.model = laptop.model
      union all
      select p.model, printer.price
      from product p join
           printer 
           on p.model = printer.model
    ) m
order by m.price desc
limit 1;

但是,由于不需要join,所以这是复杂的方法:

select m.model, m.price
from (select pc.model, pc.price
      from pc 
      union all
      select laptop.model, laptop.price
      from laptop 
      union all
      select printer.model, printer.price
      from printer 
    ) m
order by m.price desc
limit 1;