2010-03-22 128 views
2

此查詢工作正常:添加第三個表的加入

$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

你真的應該使用連接,它更清晰,它讓你的加入條件,你的where子句中。此外,當你想在添加第三個表,它更是一致的:

這是你的原代碼,使用顯式聯接語法:

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

差不多。

您的語法是爲第三個表是正確的(雖然是舊式;它使用隱式聯接)。

但是爲了讓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 
0

你將不得不增加一個GROUP BY子句與它(我只是設置在下面的例子中的登錄ID)一個或多個字段以及你在那裏使用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";