从mysql获取满足条件的行数和1个查询中的最大值

时间:2017-05-19 15:44:37

标签: mysql sql

我有下表 - 顺序:

enter image description here

目前使用以下查询:

select `id` 
from `order` 
where `userid_FK`=24242 and `productid_FK`=5 

返回 - 32,33,34

如何在一个查询中选择max(price)197.0000这是否可能(该用户和productid的最高价格)?

由于

2 个答案:

答案 0 :(得分:1)

您需要使用MAX

这将为您提供一行的最高价格。

select `id`,max(price) 
from `order` 
where `userid_FK`=24242 and `productid_FK`=5 

如果你想要所有记录:

select `id`,(select max(price) 
from `order` 
where `userid_FK`=24242 and `productid_FK`=5) ) as maxrate
from `order` 
where `userid_FK`=24242 and `productid_FK`=5 

答案 1 :(得分:1)

一种方法是在选择列表中使用子查询

select `id`, (select max(price) from `order` where `userid_FK`=24242 and `productid_FK`=5) as maxprice
from `order` 
where `userid_FK`=24242 and `productid_FK`=5