如何向此MySQL查询添加LEFT JOIN?

时间:2010-07-02 20:13:02

标签: mysql join left-join

我是初学者所以请原谅我,如果对你们这些人来说这似乎有点容易。

所以,我在这里有这个问题:

SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
                    code_tags.*, 
                    tags.*, 
                    users.firstname AS authorname, 
                    users.id AS authorid,
                    GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
                    FROM code, code_tags, tags, users
                    WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
                    GROUP BY code_id
                    ORDER BY date DESC

非常激烈。我想从表格评论中计算code提交的评论数量。我无法将其添加为WHERE comments.codeid = code.id,因为这样就不会在没有评论的情况下从数据库中选择提交。

如何在LEFT JOIN comments.codeid ON code.id = comments.codeid或其他内容中添加某些内容?

谢谢!

杰克

2 个答案:

答案 0 :(得分:1)

将现有的联接更改为正确的SQL-92 JOINS,添加left join变得微不足道。

SELECT 
  code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
  code_tags.*, 
  tags.*, 
  users.firstname AS authorname, 
  users.id AS authorid,
  GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM 
  code
  join code_tags on code_tags.code_id = code.id
  join tags on tags.id = code_tags.tag_id
  join users on users.id = code.author
  left join comments on comments.codeid = code.id
GROUP BY code_id
ORDER BY date DESC

请注意,作为一般经验法则,在查询中选择*被认为是个坏主意。只检索您实际需要的列。

答案 1 :(得分:0)

使用count(comments.code_id)和left join来获取注释数。 要使其正常工作,您需要按照除comments.code_id之外的所有返回列进行分组 某些数据库(例如MS Access)无法对使用*选择的字段进行分组,因此您必须按名称选择它们,然后将它们包含在组中。

例如,如果表格 code_tags 包含字段 code_id tag_id ,而表格标记包含字段 id < / strong>和标记 它应该看起来像:

SELECT code.id AS codeid, code.title AS codetitle,  
code.summary AS codesummary, code.author AS codeauthor,  
code.rating AS rating, code.date,  
code_tags.code_id, code_tags.tag_id, tags.id, tags.tag,  
users.firstname AS authorname, users.id AS authorid,  
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup  
count(comments.code_id) as NumComments  
FROM  
code JOIN code_tags ON code_tags.code_id = code.id  
JOIN tags ON tags.id = code_tags.tag_id  
JOIN users ON users.id = code.author  
LEFT JOIN comments ON comments.code_id = code.id  
GROUP BY code_id, codetitle, codesummary, codeauthor, rating, code.date,  
code_tags.code_id, code_tags.tag_id, tags.id, tags.tagName,
authorname, authorid, taggroup
ORDER BY date DESC