2012-02-22 54 views
1

我有這樣的SQL查詢: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.topdatea.date來訂購。

出了什麼問題?

+0

你這是什麼意思是通過合併'a.topdate'和'b.date'「的順序? – 2012-02-22 19:22:30

+0

所以如果b.topdate高於a.date,它會高於它。 – user1022585 2012-02-22 19:23:11

+0

然後它看起來就是你所做的:'按b.topdate desc,a.date desc'命令。 – 2012-02-22 19:25:00

回答

0

你不能把它爲了雙方b.topdate和a.date,因爲他們都有一個值。如果你可以說,當他們都有,你應該使用一個比其他(比如topdate超過日期)的值,你可以做這樣的:通過

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)

+0

謝謝,對COALESCE – user1022585 2012-02-22 19:34:06

+0

不熟悉,那麼解決您的問題呢? – 2012-02-22 19:35:54

+0

是的,它應該如此 – user1022585 2012-02-22 19:37:53

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

對我來說看起來像MySQL--而不是Oracle。從OP的問題歷史來看,它幾乎可以肯定是MySQL ... – Yuck 2012-02-22 19:27:02

+0

謝謝,我從來沒有想過檢查op的歷史,對未來是個好主意。 – northpole 2012-02-22 19:30:33

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