[英]MySQL join two tables when one table is missing a row
如何将这两个表连接在一起?
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
您有一个问题,因为默认情况下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);
这是一个SQL Fiddle,它证明这可以正确回答OP的问题。
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
正确的连接类型是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;
我有一个问题要问;)
如果表格如下所示,将会发生什么? (只是一个小小的变化)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.