从MySql中的列中选择不同的值

时间:2014-01-09 04:39:06

标签: mysql sql select group-by groupwise-maximum

假设我有一个名为items的表:

sender_id receiver_id goods_id price
  2            1          a1   1000
  3            1          b2   2000
  2            1          c1   5000
  4            1          d1   700
  2            1          b1   500   

在这里,我想从 表中按价格的降序选择sender_id,goods_id,这样就不会出现多次包含相同sender_id值的行(这里sender_id 2)。我使用了以下查询,但是徒劳无功:

select distinct sender_id,goods_id from items where receiver_id=1 order by price desc

结果显示所有五个元组(记录)的元组包含sender_id 2三次按时间降序排列。但我想要的只显示三条记录,其中一条记录的sender_id为2,最高价格为5000 。 我该怎么办? 我的预期输出是:

sender_id goods_id
   2         c1
   3         b2
   4         d1

4 个答案:

答案 0 :(得分:2)

获得每组的最高价格,您可以这样做:

SELECT T1.*
FROM (
    SELECT
     MAX(price) AS max_price,
     sender_id
    FROM items
    GROUP BY sender_id
) AS T2
INNER JOIN items T1 ON T1.sender_id = T2.sender_id AND T1.price = T2.max_price
WHERE T1.receiver_id=1 
ORDER BY T1.price

答案 1 :(得分:1)

试试这个:

SELECT i.sender_id, i.goods_id 
FROM items i 
INNER JOIN (SELECT i.sender_id, MAX(i.price) AS maxPrice
            FROM items i WHERE i.receiver_id=1 
            GROUP BY i.sender_id
           ) AS A ON i.sender_id = A.sender_id AND i.price = A.maxPrice
WHERE i.receiver_id=1

SELECT i.sender_id, i.goods_id 
FROM (SELECT i.sender_id, i.goods_id 
      FROM (SELECT i.sender_id, i.goods_id 
            FROM items i WHERE i.receiver_id=1 
            ORDER BY i.sender_id, i.price DESC
           ) AS i 
      GROUP BY i.sender_id
     ) AS i

答案 2 :(得分:0)

select distinct (sender_id,goods_id) from items where receiver_id=1 order by price desc;

你可以这样使用。

答案 3 :(得分:0)

请试试这个

select sender_id,goods_id from items t1
where not exists (select 1 from items t2
                  where t2.sender_id = t1.sender_id
                    and t2.receiver_id = t1.receiver_id
                    and t2.price > t1.price)
 and receiver_id = 1
order by price desc