将第三个表添加到Join

时间:2010-03-22 18:32:50

标签: php mysql

此查询正常工作:

$sqlStr = "SELECT s.loginid, s.title, s.url, s.displayurl, l.username
             FROM submission AS s,
                  login AS l
            WHERE s.loginid = l.loginid
         ORDER BY s.datesubmitted DESC
            LIMIT 10";

如果我想加入第三个MySQL表(称为“注释”),它会工作吗?

$sqlStr = "SELECT s.loginid, s.submissionid s.title, s.url, s.displayurl, l.username, count(c.comment) countComments
             FROM submission AS s,
                  login AS l, 
                  comment AS c,
            WHERE s.loginid = l.loginid
              AND s.submissionid = c.submissionid
         ORDER BY s.datesubmitted DESC
            LIMIT 10";

提前致谢,

约翰

3 个答案:

答案 0 :(得分:3)

你应该真正使用连接,它更清晰,它可以使你的连接条件超出你的where子句。此外,当您想要添加第3个表时,它更加一致:

这是您的原始代码,使用显式连接语法:

SELECT      s.loginid, s.title, s.url, s.displayurl, l.username
FROM        submission s
INNER JOIN  login l ON l.loginid = s.loginid
ORDER BY    s.datesubmitted DESC
LIMIT       10

然后,如果你想添加第三个表,那很简单:

SELECT      s.loginid, s.title, s.url, s.displayurl, l.username
FROM        submission s
INNER JOIN  login l ON l.loginid = s.loginid
INNER JOIN  comment c ON s.submissionid = c.submissionid
ORDER BY    s.datesubmitted DESC
LIMIT       10

另外,这是一个技巧。如果您加入的两列名称相同,则可以使用USING语法:

INNER JOIN  login l USING (loginid)
INNER JOIN  comment c USING(submissionid)

答案 1 :(得分:1)

几乎。

你的语法是第三个表是正确的(虽然旧式;它使用隐式JOIN)。

但是要使COUNT(c.comment)工作,你必须(或者我应该说“应该”,因为MySQL在某些语法上是松散的)在选择中添加GROUP BY子句。该子句应该为SELECT中的每个其他列命名:

SELECT s.loginid, s.submissionid s.title, s.url, 
       s.displayurl, l.username, count(c.comment) AS countComments
FROM submission AS s,
     login AS l, 
     comment AS c,
WHERE s.loginid = l.loginid AND s.submissionid = c.submissionid
GROUP BY s.loginid, s.submissionid s.title, s.url, s.displayurl, l.username
ORDER BY s.datesubmitted DESC
LIMIT 10

答案 2 :(得分:0)

你必须添加一个带有一个或多个字段的GROUP BY子句(我在下面的例子中只设置了loginid)以及你在那里使用COUNT()函数,所以SQL会是这样的:

$sqlStr = "SELECT s.loginid, s.submissionid s.title, s.url, s.displayurl, l.username, count(c.comment) countComments
             FROM submission AS s,
                  login AS l, 
                  comment AS c
            WHERE s.loginid = l.loginid
              AND s.submissionid = c.submissionid
         GROUP BY s.loginid
         ORDER BY s.datesubmitted DESC
            LIMIT 10";