2012-02-22 64 views
0

是否可以從SQL語句中的子查詢中提取2個結果?SQL從子查詢中提取

我:

"SELECT 
    (SELECT bid FROM auction_bids WHERE itemID=a.id ORDER BY bid DESC LIMIT 1) as topbid, 
    a.* FROM auction_items a ORDER BY a.date DESC LIMIT 15" 

它返回topbid的一部分,我也希望它拉不僅bid(如topbid),而且還date(如topdate)爲好。我怎樣才能做到這一點?我需要另一個子查詢嗎?還是可以將它們合併爲一個?

+0

而不是去交叉連接,,它是非常容易與上述功能SELECT * FROM T1 LEFT JOIN比較(T2,T3,T4) ON( t2.a = t1.a AND t3.b = t1.b AND t4.c = t1.c) – 2012-02-22 17:10:00

回答

0

從屬子查詢(取決於外部的某些值,如您的案例中的a.id)不是一種在子集中查找最大值的非常有效的方法。

而是使用子查詢與GROUP BY:

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 a.date DESC 
LIMIT 15 
+0

謝謝.................... – user1022585 2012-02-22 18:56:24

+0

aegh,Im試圖通過'b.topdate'和'a.date'來命令它們(當item被添加時),但它並沒有命令它們正確:''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「 – user1022585 2012-02-22 19:09:10