如何在单行中获取最小值和最大值以及对应的ID

时间:2019-01-07 10:20:50

标签: mysql sql sql-order-by

我有一个名为product的表,其中包含3个字段:

prod_id  price  pname
1        100    abc
2        200    bbc
3        300    cbc

我要在一行中获取最小值和最大值的数据,即:

 minprice  prod_id1   maxprice   prod_id2
 100       1          300        3

我尝试使用以下查询,但无法找到确切结果(如果我有更多数据)

SELECT s1.prod_id as prod_id1, 
       s2.prod_id as prod_id2, 
       min(s1.price) as minprice,
       max(s2.price) as maxprice 
FROM product s1
INNER JOIN product s2 ON s1.prod_id = s2.prod_id

3 个答案:

答案 0 :(得分:2)

您可以使用LIMIT进行此操作:

SELECT
    pmin.price AS minprice, 
    pmin.prod_id AS minprice_prodid,
    pmax.price AS maxprice,
    pmax.prod_id AS maxprice_prodid
FROM (
    SELECT prod_id, price FROM product ORDER BY price LIMIT 1
) pmin
CROSS JOIN (
    SELECT prod_id, price FROM product ORDER BY price DESC LIMIT 1
) pmax

答案 1 :(得分:1)

您可以在下面尝试-

new R()

答案 2 :(得分:1)

SELECT s1.prod_id as prod_id1, 
       s2.prod_id as prod_id2, 
       s1.price as maxprice,
       s2.price as minprice 
FROM products s1
INNER JOIN products s2 ON s1.price > s2.price
order by s1.price desc, s2.price asc
limit 1

Demo