我有两个表“列表”和“出价”。我有一个查询,它会返回特定用户出价的所有商家信息,其中end_date已过去。我需要做的是进一步限制结果,只查找用户出价的列表,并且是最后一个出价者。这是我到目前为止的查询...
SELECT listings.end_date, listings.user_id, listings.title, listings.auc_fp, listings.id, listings.auc_image1
FROM listings INNER JOIN bids ON listings.id = bids.listing_id
WHERE bids.user_id=$userid
AND listings.end_date < NOW()
ORDER BY list_ts DESC"
我对子查询不满意,我假设我需要在这里查找“出价”表中的所有用户出价,其中bid_ts(出价时间戳)是相应listing_id的最新时间戳在出价表中。我的出价表中的列为:listing_id,user_id,bid,bid_ts。
+------------+---------+------+---------------------+
| listing_id | user_id | bids | bid_ts |
+------------+---------+------+---------------------+
| 1 | 10 | 100 | 2012-11-16 00:54:03 |
| 1 | 11 | 101 | 2012-11-16 00:54:04 |
| 2 | 10 | 33 | 2012-11-16 00:54:03 |
| 2 | 11 | 34 | 2012-11-16 00:54:04 |
| 2 | 12 | 35 | 2012-11-16 00:54:05 |
+------------+---------+------+---------------------+
感谢您的帮助
答案 0 :(得分:4)
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT listing_ID, user_ID, MAX(bid_ts) maxDate
FROM tableName
GROUP BY listing_ID, user_ID
) b ON a.listing_ID = b.listing_ID AND
a.user_ID = b.user_ID AND
a.bid_ts = b.maxDate