2012-12-25 45 views
0

所以我有以下查詢:如何使用MySQL的加入/計數正確

'SELECT *, upload.id AS id, report.id AS report_id, (SELECT COUNT(*) 
    FROM upload WHERE report.upload_id = upload.id) AS nums FROM upload 
    LEFT JOIN report ON upload.id=report.upload_id WHERE private="0" ' 
我有多麼每次上傳的報告正在計算的問題

此查詢需要計算給定上載的所有報告,並在提取時返回所有上載。由於某種原因,每次插入新報告而不是添加到總數時,我都會得到重複的上傳。見下圖:

enter image description here

注意如何控制檯(1)巴紐顯示了三次,每次相關於給定載報告......我真的希望它一旦出現,然後計數一邊應該是(3)。任何幫助將非常感激!!

+1

您可以嘗試使用DISTINCT關鍵字(SELECT DISTINCT ... http://www.mysqlfaqs.net/mysql-faqs/SQL-Statements/Select-Statement/How-does-DISTINCT-work-in-MySQL ),或者您可以簡單地左連接並統計upload.id條目,並通過GROUP BY(http://www.tizag.com/mysqlTutorial/mysqlcount.php)將其分組。 – dash

回答

0

SQL Fiddle進行測試。

只需使用左連接和計數report.upload_id小號

select u.filename, u.filesize, COUNT(r.upload_id) as reports 
from upload u 
left join report r on u.id=r.upload_id 
group by u.id, u.filename, u.filesize 

我離開了where private = "0",因爲你沒有指定它所屬。

+0

這是行得通的,但由於某種原因,如果報告的最後一行與用戶的IP不匹配,那麼它將允許它們再次提交報告。我認爲這可能與我的PHP抓取有關 – KraigBalla

0

如果你需要爲每個上傳的報告只是數量,你不需要加入他們,你可以這樣做:

SELECT upload.*, 
     (SELECT COUNT(*) FROM report WHERE report.upload_id = upload.id) AS nums 
FROM upload 

,或者你可以這樣做:

SELECT upload.id, upload.name, count(*) as nums 
FROM upload 
    INNER JOIN report ON report.upload_id = upload.id 
GROUP BY upload.id, upload.name 

這將返回所有帶有報告的上傳。要獲得有或沒有報告的上傳,你需要一個左連接:

SELECT upload.id, upload.name, count(report.id) as nums 
FROM upload 
    left JOIN report ON report.upload_id = upload.id 
GROUP BY upload.id, upload.name 

這裏是一個SQL Fiddle與查詢。

+0

這是針對每次上傳和所有上傳的報告數量的。 – KraigBalla

+0

您的第二個查詢適用,但不會返回沒有任何報告的上傳。任何想法如何添加? – KraigBalla

+0

使用OUTER JOIN而不是INNER JOIN,並將'WHERE'改爲'ON'。 – Barmar

0

SELECT COUNT(upload.id),report.id 從報告,上傳 LEFT JOIN報告ON upload.id = report.upload_id WHERE私人= 「0」 組由report.id

0
SELECT 
    upload.id, 
    upload.name, 
    count(1) as nums 
FROM 
    upload 
LEFT OUTER JOIN 
    report ON 
    report.upload_id = upload.id 
GROUP BY 
    upload.id, 
    upload.name 
+0

什麼表是私人的?如果它在'upload'表中,則在private =「0」中添加一個'where'子句。如果它是報告表的一部分,並且它位於左側外部聯接 – Lock