Mysql SQL:完全外部联接不工作
我有两张桌子,一张是空的,另一张不是Mysql SQL:完全外部联接不工作,mysql,sql,database,join,Mysql,Sql,Database,Join,我有两张桌子,一张是空的,另一张不是 hugot_投票统计: hugot_comment_统计:空 我知道我不能使用内部联接,因为它只匹配ON部分中指定的值。在这种情况下,一个表没有值 SELECT t0.hugot_id as hugot_id, t0.upvotes as upvotes, t1.comment_count as comment
- hugot_投票统计:
- hugot_comment_统计:空
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
这就是我使用完全连接的部分。我所期望的是,如果没有找到空表,则空表(在本例中为comment_count)将显示一个默认值(即:0)
然而,我得到了一个错误,正如您可以看到的1064——您的SQL语法有一个错误;查看与您的MySQL服务器版本对应的手册,以了解要使用的正确语法。MySQL没有syntax关键字
完全外部联接。
您必须使用左联接和右联接的组合才能获得完全联接
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
您可以使用以下内容来显示您的信息:
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
您之所以会遇到这个错误,是因为MySQL不支持(或识别)完整外部连接语法 但是,可以在MySQL中模拟完整的外部连接 我们实际上需要两个查询 一个查询返回左侧表中的所有行。(左外连接。) 我们需要将第二个查询的结果追加到该查询之后,这看起来与第一个查询一样,只是我们需要右侧的表作为驱动程序,并且需要删除所有匹配的行(以避免重复第一个查询中返回的行) 我们使用
UNION-ALL
set操作符将第二个查询的结果附加到第一个查询
例如:
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
返回不匹配的行。这就是我要找的。非常感谢。虽然upvots也可以为null。但我需要ifnull函数。