0

我有一个要查询信息的出价表。
表结构是:id、item_id、price、date、user_id
许多用户在这张表上出价。我需要找到所有 item_id 的列表,其中包含收到的最高价格以及同一商品的第二个最高价格。

这是我到目前为止所拥有的

SELECT item_id, MAX(price) as MAX, (SELECT MAX(price) FROM TABLE GROUP BY item_id, LIMIT 1,1) FROM TABLE WHERE date > 2013-01-01 GROUP BY item_id  

我错过了什么

这是我得到的结果

item_id    MAX    USER_ID    MAX(PRICE)
1          17222     122       22500
2          15888     161       22500

对于我所有的下一个项目,第二个始终是 22500,我怎样才能获得第二个最佳出价的真正第二个值?

4

2 回答 2

0

这是另一种机制,使用substring_index()/group_concat()技巧。大概,您还想要最高价格的用户,而您的查询没有这样做。尝试这个:

select item_id, max(price) as maxprice,
       substring_index(group_concat(user_id order by price desc), ',', 1) as user_id,
       substring_index(substring_index(group_concat(price order by price desc),
                                       ',', 2),
                       ',', -1) as secondprice
from t
group by item_id;
于 2013-09-17T15:07:21.513 回答
0

好的,这是经过测试的。试试看:

SELECT t1.item_id, 
MAX(t1.price) AS MAX1, 
(SELECT t2.price FROM TABLE AS t2 WHERE t2.item_id = t1.item_id ORDER BY t2.price DESC LIMIT 1,1) AS MAX2 
FROM TABLE AS t1 
WHERE t1.date > 2013-01-01 
GROUP BY t1.item_id
于 2013-09-17T14:48:16.073 回答