2014-01-05 51 views
-1

我有3個表:'新聞','評論'和'擦'。我需要從'新聞'獲取所有數據,從'擦'獲得'標題'並計算每條新聞的評論數量。如何從3個表中獲取數據?

現在我無法從'擦'獲得'標題'。下面的代碼工作:

SELECT n.id,n.header,n.text, COUNT(c.news_id) AS comments 
FROM news n 
LEFT JOIN comments c ON n.id = c.news_id 
GROUP BY n.id 
ORDER by n.id 
LIMIT 30 

但我需要類似的東西,這代碼不起作用(調用一個成員函數fetch_array()一個非對象):

SELECT n.id,n.header,n.text,r.title COUNT(c.news_id) AS comments 
FROM news n,rub r 
LEFT JOIN comments c ON n.id = c.new_id AND r.news_id=n.id 
GROUP BY n.id ORDER by n.id 
LIMIT 30 

如何修理它?

+1

你缺少一個逗號','在你的第二個了'COUNT'功能之前,聲明。我們看不到您的PHP代碼,但我認爲您在獲取結果之前沒有檢查數據庫錯誤。 – halfer

+0

等錯別字。你做錯了什麼halfter寫道:你甚至不問數據庫有關具體的錯誤給出。你是盲目的。您需要將其作爲錯誤的數據庫。另請參閱此錯誤的許多重複項:https://stackoverflow.com/search?q=Call+to+a+member+function+fetch_array%28%29+on+a+non-object – hakre

+0

@Narendra,收縮「我是」應該有一個撇號';-)' – halfer

回答

0

我不清楚你在問什麼,但你需要另一個JOIN。而你需要移動的連接條件的rub表到JOIN關鍵字,不進的連接條件的comments

SELECT n.id, 
     n.header, 
     n.text, 
     r.title, -- comma was missing (as halfer mentioned) 
     COUNT(c.news_id) AS comments 
FROM news n 
    JOIN rub r ON r.news_id=n.id --- this is missing 
    LEFT JOIN comments c ON n.id = c.new_id -- no join condition for rub/news here 
GROUP BY n.id 
ORDER by n.id 
LIMIT 30 

你的GROUP BY運營商的使用也是錯誤的。上述查詢將(正確)被所有其他DBMS拒絕。

請閱讀以下理解爲什麼你GROUP BY是錯誤的:

+0

是的,我做了一分鐘前! – aspermag