2016-07-13 25 views
1

,我需要從目錄中的所有信息,請加入參數表,並加入到意見表,再算上通過目錄發佈的評論,我的SQL查詢:三表的連接和計數顯示我有3個表錯誤的結果

SELECT 
    catalog.catalog_id, 
    catalog.slug, 
    catalog.title, 
    catalog.city, 
    catalog.street, 
    catalog.image COUNT(ratings.rate) AS votes, 
    COUNT(comments.catalog_id) AS total_comments, 
    ROUND(SUM(ratings.rate)/COUNT(ratings.rate)) AS average 
FROM 
    catalog 
LEFT JOIN ratings ON ratings.object_id = catalog.catalog_id 
LEFT JOIN comments ON comments.catalog_id = catalog.catalog_id 
GROUP BY 
    catalog.catalog_id 
ORDER BY 
    average, 
    votes DESC 

一切都顯示很好只有total_comments壞數字6,但在評論表中只有2行,所以它的壞結果。我認爲這是分組的問題。我試過添加GROUP BY catalog.catalog_id, comments.catalog_id,但沒有幫助。 我的表:

enter image description here

回答

2

的問題是,你有多個評級和評論,所以你得到的每一個職位的笛卡爾乘積。

正確的解決方案是在加入前預先聚合數據。

SELECT c.*, r.votes, c.total_comments, 
     ROUND(sumrate/votes) AS average 
FROM catalog c LEFT JOIN 
    (SELECT r.object_id, COUNT(*) as votes, SUM(r.rate) as sumrate 
     FROM ratings r 
     GROUP BY r.object_id 
    ) r 
    ON r.object_id = c.catalog_id LEFT JOIN 
    (SELECT c.catalog_id, COUNT(*) as total_comments 
     FROM comments c 
     GROUP BY c.catalog_id 
    ) c 
    ON c.catalog_id = c.catalog_id 
GROUP BY c.catalog_id 
ORDER BY average, votes DESC; 
+0

是的,它的工作原理!結果幾乎是好的,但現在我沒有理解爲什麼排序不能正確地使用「ORDER BY average,votes DESC」工作,因爲我需要最高的平均值,並且投票是從頂部到機器人,但是DESC並沒有解決什麼東西。我的結果是var_dump http://pastie.org/private/exg0mzscvgv4faiuhrobuq最後在機器人中最高,而不是最高。 – SkySonny

+0

@SkySonny。 。 。如果這可以產生正確的數字,我建議您詢問另一個關於排序的問題。 –

相關問題