SQL:全外连接不起作用

7

我有两张表,其中一张为空,而另一张不为空。

我知道不能使用内连接(Inner JOIN),因为它只匹配ON部分指定的值。在这种情况下,一个表没有值。

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
FULL OUTER JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

这是我使用FULL JOIN解决的部分。我原本期望的是,如果没有找到数据,空表(在这种情况下是comment_count)将显示默认值(即0)。
然而,如你所见,我收到了一个错误1064 - 你的SQL语法有误,请检查与您的MySQL服务器版本相对应的手册以获取正确的语法。
3个回答

13

MySQL没有语法关键字FULL OUTER JOIN。 您必须使用LEFT JOIN和RIGHT JOIN的组合来获取完整的连接。

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
LEFT JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

UNION ALL 

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
RIGHT JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

7
您之所以出现这个错误,是因为MySQL不支持(或者无法识别)FULL OUTER JOIN语法。
但是,在MySQL中可以模拟FULL OUTER JOIN。
实际上,我们需要两个查询语句。
一个查询语句返回左侧表格的所有行。(左外连接。)
我们需要将第二个查询的结果追加到第一个查询的结果中,第二个查询与第一个查询非常相似,只是我们需要将右侧表格作为驱动表格,并且需要排除所有已匹配的行(以避免在第一个查询中返回重复的行)。
我们使用UNION ALL集合运算符将第二个查询的结果追加到第一个查询的结果中。
例如:
SELECT t0.hugot_id                     AS hugot_id
     , t0.upvotes                      AS upvotes
     , t1.comment_count                AS comment_count
  FROM hugot_votes_stats t0
  LEFT
  JOIN hugot_comment_stats t1
    ON t0.hugot_id = t1.hugot_id

 UNION ALL

SELECT t0.hugot_id                     AS hugot_id
     , t0.upvotes                      AS upvotes
     , t1.comment_count                AS comment_count
  FROM hugot_votes_stats t0
 RIGHT
  JOIN hugot_comment_stats t1
    ON t0.hugot_id = t1.hugot_id
 WHERE t0.hugot_id IS NULL

注意第二个查询中WHERE子句中的谓词。这将过滤掉所有已经找到匹配的行。(这些行已经被第一个查询返回;第二个查询使用了“反连接”模式来返回t1中没有匹配的行。)

4
您可以使用以下内容来展示您的信息:
SELECT  t0.hugot_id,
        t0.upvotes,
        ifnull(t1.comment_count,0) as commentcount
FROM
    hugot_votes_stats as t0
left join
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

1
这就是我要找的。非常感谢。尽管 upvotes 也可以为空,但是 ifnull 函数是我需要的。 - Mr A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接