当一个表缺少一行时,MySQL会连接两个表

时间:2014-12-09 19:11:39

标签: mysql

如何将这两张表连在一起?

type count
NULL 117
2    1

type count
NULL 807
1    3
2    32

我尝试过INNER JOIN,LEFT JOIN和RIGHT JOIN,我无法弄明白。我希望最终结果看起来像

type count count
NULL 117   807
1    NULL  3
2    1     32

4 个答案:

答案 0 :(得分:1)

您遇到问题,因为NULL默认情况下不匹配。但是,你可以让它们匹配。我假设第一个是t1,第二个是t2

select t2.type, t1.count, t2.count
from t2 left join
     t1
     on t2.type = t1.type or (t2.type is null and t1.type is null);

Here是一个SQL小提琴,它表明这正确回答了OP的问题。

答案 1 :(得分:1)

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

Sourced from this question

答案 2 :(得分:0)

正确的连接类型是FULL OUTER JOIN,但它在MySQL中不存在。 我们可以通过以下方式模拟它:

SELECT t1.type, t1.count, t2.count  # exact matches
FROM t1 join t2 on t1.type = t2.type
UNION
select t1.type, t1.count, NULL      # t2 not present
FROM t1 left join t2 on t1.type = t2.type
WHERE t2.type IS NULL
UNION
select t2.type, NULL, t2.count      # t1 not present
FROM t2 left join t1 on t2.type = t1.type
WHERE t1.type IS NULL
UNION 
select NULL, t1.count, t2.count # NULL on both sides
FROM t1, t2
WHERE t1.type IS NULL and t2.type IS NULL;

答案 3 :(得分:0)

我对这个问题有疑问;)

如果表格如下所示会发生什么? (只是一个小小的变化)

type count
NULL 117
3    333
2    1

type count
NULL 807
1    3
2    32

因为在这种情况下,两个表都包含与另一个表不匹配的记录,所以可能从一个方向连接是不够的,您需要从两个方向连接表,但是,您可能无法使用数据'类型'只有一张桌子......

所以一个解决方案可能是:

select if (t1.type is null, t2.type, t1.type) as type, t1.count count1, t2.count count2
  from t1
  left join t2 
    on t1.type=t2.type or (t1.type is NULL and t2.type is NULL)
union
select if (t1.type is null, t2.type, t1.type) as type, t1.count count1, t2.count count2
  from t1
  right join t2
    on t1.type=t2.type or (t1.type is NULL and t2.type is NULL);

此外,

  • 您也可以使用coalesce()功能代替if (.. is null, ...),例如coalesce(t1.type, t2.type)
  • 你可能仍然需要小心union,也许你想保留重复的记录(如果有的话)并使用union all

http://www.sqlfiddle.com/#!2/302e69/2