如何从3个表中获取数据?

时间:2014-01-05 09:55:16

标签: php mysql select mysqli

我有3张桌子:'新闻','评论'和'擦'。我需要从'news'获取所有数据,从'rub'获取'title'并计算每条新闻的评论数量。

现在我无法从'rub'获得'title'。以下代码有效:

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 个答案:

答案 0 :(得分: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错误的原因: