2012-06-05 81 views
0

我有以下查詢。查詢返回不正確的計數

SELECT a.link_field1 AS journo, count(a.link_id) as articles, AVG(b.vote_value) AS score FROM dan_links a LEFT JOIN dan_votes b ON link_id = vote_link_id WHERE link_field1 <> '' and link_status NOT IN ('discard', 'spam', 'page') GROUP BY link_field1 ORDER BY link_field1, link_id 

此查詢返回列表中第一項的計數爲3。什麼應該返回是

Journo | count | score 
John S | 2 | 6.00 
Joe B | 1 | 4 

不過,對於第一個約翰·S,它返回的3

計數如果我直接查詢

select * from dan_links where link_field1 = 'John S' 

我得到2分返回的記錄,因爲我會期望。我不能爲我的生活找出爲什麼計數是錯誤的,除非由於某種原因它正在計算dan_vote表中的記錄

我如何得到正確的計數,或者是我的查詢完全錯誤?

編輯:表格的內容

dan_links

link_id | link_field1 | link | source | link_status 
1 | John S | http://test.com | test.com | approved 
2 | John S | http://google.com | google | approved 
3 | Joe B | http://facebook.com | facebook | approved 

dan_votes

vote_id | link_id | vote_value 
1 | 1 | 5 
2 | 1 | 8 
3 | 2 | 4 
4 | 3 | 1 

編輯:它看起來像它正指望在投票表中的行出於某種原因

+0

發佈您正在使用的記錄(來自2個表格)會很有幫助。 – codingbiz

+0

歡呼聲我補充說 – Dannymh

+0

以上所以我刪除了投票表中的link_id 1的記錄之一,並且計數以2進入,這是正確的,但我不明白爲什麼它會這樣做,因爲我的計數是在.link_id – Dannymh

回答

0

當您在執行條件爲link_id = vote_link的左外連接時_id用於創建的每個匹配的記錄一行,就像

link_id | link_field1 | link | source | link_status|vote_id|vote_value 
1 | John S | http://test.com | test.com | approved|1|5 
1 | John S | http://test.com | test.com | approved|2|8 
2 | John S | http://google.com | google | approved|3|4 
3 | Joe B | http://facebook.com | facebook | approved|4|1 

一些東西現在,當你通過link_field1做組,你得到算作3約翰小號

嵌套查詢可能工作

SELECT journo,count(linkid) as articles,AVG(score) FROM 
(SELECT a.link_field1 AS journo, AVG(b.vote_value) AS score, a.link_id as linkid 
FROM dan_links a 
LEFT JOIN dan_votes b 
ON link_id = vote_link_id 
WHERE link_field1 <> '' 
and link_status NOT IN ('discard', 'spam', 'page') 
GROUP BY link_id 
ORDER BY link_field1, link_id) GROUP BY journo 

上面的查詢會提供不正確的平均值作爲((N1 + N2)/ 2 + N3)/ 2!=(N1 + N2 + N3)/ 3,所以使用下面查詢

SELECT journo,count(linkid) as articles, SUM(vote_sum)/SUM(count(linkid)) 
FROM 
    (SELECT a.link_field1 AS journo, SUM(b.vote_value) AS vote_sum, a.link_id as linkid, count(a.link_id) as count_on_id 
    FROM dan_links a 
    LEFT JOIN dan_votes b 
    ON link_id = vote_link_id 
    WHERE link_field1 <> '' 
    and link_status NOT IN ('discard', 'spam', 'page') 
    GROUP BY link_id 
ORDER BY link_field1, link_id) GROUP BY journo 

希望這會有所幫助。

+0

好吧,有沒有一種方法可以在同一個查詢中查詢與查詢前半部分匹配的記錄,即 從dan_links中選擇count(*)where link_field1 ='John S' 沒有我單獨查詢那個數字? – Dannymh

+0

一種方法是首先根據link_id進行分組,以便重複記錄可以小心謹慎,然後根據link_field1對結果進行分組以獲得計數。通過示例查詢更新了答案 – coder

相關問題