mysql连接表,查询只返回匹配行的行

时间:2012-08-12 22:23:07

标签: mysql join

目前我有这个mysql:

$result = mysql_query("SELECT blog.id, blog_comments.cid, blog.name,
  blog.blogtext, blog.date, blog.like, blog.dislike, blog_comments.comment, blog_comments.date
FROM blog, blog_comments  
WHERE blog.id = blog_comments.cid   
ORDER BY blog.id DESC LIMIT 30")

查询返回行及其注释,问题是:它只返回带有注释的行,它不会返回没有注释的行。我找到了一些主题,并发现我可能应该使用FULL OUTER JOIN。现在我试图应用这个,没有成功。

非常感谢协助

1 个答案:

答案 0 :(得分:3)

而不是隐式连接(以逗号分隔的表列表产生INNER JOIN),而是使用显式LEFT JOIN

SELECT 
  blog.id,
  blog_comments.cid,
  blog.name,
  blog.blogtext,
  blog.date, 
  blog.like, 
  blog.dislike, 
  blog_comments.comment, 
  blog_comments.date
FROM 
 blog
 /* LEFT JOIN will return rows from blog (the "left" side of the join) even if no 
    related rows exist in blog_comments (the "right" side of the join) */
 LEFT JOIN blog_comments ON blog.id = blog_comments.cid   
ORDER BY blog.id DESC
LIMIT 30