2013-06-30 50 views
-1

我想查詢有在對方的外鍵來顯示有條件的結果兩個表,我的表如下:PHP的MySQL如何運行以正確的方式子查詢該表

auction_bids表:

id applicant_id bid auction_id owner.id 

拍賣表:

id user_id title description 

結果我需要顯示給登錄的用戶是:

title applicant_id [how many bids the project has] auction_id 

我現在不工作的查詢是:

SELECT (SELECT COUNT(auction_bids.owner_id) 
      FROM auction_bids 
     WHERE auction_bids.owner_id = ".$_SESSION['userid']." 
     ) AS count, auction_bids.* 
    FROM auction_bids 
WHERE auction_bids.owner_id = ".$_SESSION['userid']." 

我不能讓每一個拍賣的出價次數在數據庫隨標題 謝謝

+0

[不要忘記**採取SO遊**它會引導你如何最好地使用SO](http://stackoverflow.com/about) – Prix

回答

0

此人將列出所有申請人及其在所有拍賣所選用戶的總出價有:

SELECT a.title, b.applicant_id, COUNT(b.applicant_id) AS bids, a.id 
    FROM auction_bids b 
    JOIN auctions a ON a.id = b.auction_id 
    WHERE b.owner_id = ".$_SESSION['userid']." 
GROUP BY b.applicant_id 

See a live DEMO here.

記住你對你的問題,你有owner.id一樣,而在這裏我有一個下劃線,因爲你需要owner_id改變它。

根據您對其他答覆的意見,您可能希望針對您的問題提出不同的結果。

這其中將列出用戶的所有拍賣與招標總量,拍賣標題和編號:

SELECT a.title, COUNT(b.applicant_id) AS total_bids, a.id 
    FROM auction_bids b 
    JOIN auctions a ON a.id = b.auction_id 
    WHERE b.owner_id = ".$_SESSION['userid']." 
GROUP BY b.auction_id 

See a live DEMO here.

+0

我使用了這一個,我只改變了程序,然後它工作得很好。 非常感謝。我想指出,但它說我沒有足夠的觀點。再次感謝你們所有人。 – Justin

0

我想你想要一個GROUP BY

SELECT a.title, ab.applicant_id, COUNT(*), a.id 
FROM auction a JOIN 
    auction_bids ab 
    ON a.id = ab.auction_id 
WHERE a.user_id = ".$_SESSION['userid']." 
GROUP BY a.id 
+0

謝謝戈登,但那是錯誤的計數。我需要通過owner_id – Justin

+0

@Justin發佈的單次拍賣獲得多少出價。 。 。業主不能有多個拍賣?您如何傳遞拍賣ID? –

+0

是的,他這樣做是我陷入困境。可以說MIKE有4次拍賣,第一次拍賣有10次出價,第二次有20次,第三次有5次,第四次有40次。 MIKE在他登錄時應該看到: title:auction1,bid:10 auction_id-1 title:auction2,bids:20 auction_id-2 title:auction3,bids:5 auction_id-3 title:auction4,bids:40 auction_id-4 我不需要申請人ID – Justin