我有这个SQL查询:
SELECT b.topbid, b.topdate, a.*
FROM auction_items a
LEFT JOIN
(SELECT itemID, MAX(bid) as topbid,
MAX(date) as topdate FROM auction_bids GROUP BY itemID ) b
ON a.id = b.itemID
ORDER BY b.topdate DESC, a.date DESC LIMIT 20
它没有订购我喜欢它的方式。我想通过合并b.topdate
和a.date
来订购。
有什么问题?
答案 0 :(得分:1)
你的意思是通过连接两个值来排序吗?如果是,请尝试以下方法:
SELECT b.topbid, b.topdate, a.*
FROM auction_items a
LEFT JOIN
(SELECT itemID, MAX(bid) as topbid,
MAX(date) as topdate FROM auction_bids GROUP BY itemID ) b
ON a.id = b.itemID
ORDER BY b.topdate || a.date DESC LIMIT 20
我不确定您使用的是哪种RDBMS,但Oracle连接是管道||
编辑:如果使用MySQL,请使用CONCAT功能:
SELECT b.topbid, b.topdate, a.*
FROM auction_items a
LEFT JOIN
(SELECT itemID, MAX(bid) as topbid,
MAX(date) as topdate FROM auction_bids GROUP BY itemID ) b
ON a.id = b.itemID
ORDER BY CONCAT(b.topdate,a.date) DESC LIMIT 20
答案 1 :(得分:0)
你不能通过b.topdate和a.date订购它,因为它们都可以有一个值。如果你可以说当它们都有一个值,你应该使用一个而不是另一个(例如topdate over date),你可以这样做:
SELECT b.topbid, b.topdate, a.*
FROM auction_items a
LEFT JOIN
(SELECT itemID, MAX(bid) as topbid,
MAX(date) as topdate FROM auction_bids GROUP BY itemID ) b
ON a.id = b.itemID
ORDER BY COALESCE(b.topdate, a.date) DESC LIMIT 20
请注意订单。如果相反,请将其作为COALESCE(a.date,b.topdate)
答案 2 :(得分:0)
尝试使用CASE语句选择一个或另一个,然后按该值排序:
SELECT b.topbid, b.topdate, a.* , CASE WHEN b.topdate > a.date then b.topdate ELSE a.date END AS oDate
FROM auction_items a
LEFT JOIN
(SELECT itemID, MAX(bid) as topbid,
MAX(date) as topdate FROM auction_bids GROUP BY itemID ) b
ON a.id = b.itemID
ORDER BY oDate DESC LIMIT 20