Mr *_*r A 2 mysql sql database join
我有两张桌子,其中一张是空的,而另一张则不是.
我知道我不能使用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
Run Code Online (Sandbox Code Playgroud)
这是我使用FULL JOIN计算的部分.我所期待的是,如果没有找到空表,那么空表(在本例中为comment_count)将显示默认值(即:0).
然而,我得到一个错误,你可以看到1064 - 你的SQL语法有错误; 查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法
MySQL没有语法关键字FULL OUTER JOIN.你必须使用LEFT和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
Run Code Online (Sandbox Code Playgroud)
您收到该错误是因为 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
Run Code Online (Sandbox Code Playgroud)
请注意第二个查询的 WHERE 子句中的谓词。这会过滤掉找到匹配项的所有行。(这些行已经由第一个查询返回;第二个查询使用“反连接”模式返回t1没有匹配的行。