【发布时间】:2015-12-15 06:35:03
【问题描述】:
我有一张桌子
ID | Name | City
1 |Jack | Null
2 |Tom | Null
还有表 b
ID | Name | City
1 |Jack | Dever
2 |Tom | Dallas
如果这两个表在表 a 中不为空,我需要编写一个查询来按 id、name 和 city 连接这两个表。但是这三列中的任何一列对于每一行都可能为空。
我在下面写了一个,但是当数据增长时性能很差
Select * from a, b
Where (a.id is not null and a.id=b.id or a.id is null) and
(a.name is not null and a.name=b.name or a.name is null) and
(a.city is not null and a.city=b.city or a.city is null)
基本上,当表a中的列不为空时,我需要加入该列。 你能对此有所了解吗? 非常感谢!
【问题讨论】:
-
您没有使用任何连接条件吗?如果你不这样做,那么你将得到笛卡尔积。因此,如果表
A有 100 行,而表B有 100 行,那么您将获得不带任何 where 子句的100*100 = 10000行。你真的想这样做吗?你给出的查询是否得到了预期的结果? -
我认为这个查询和join条件是一样的,不是吗?我的期望不是笛卡尔,只是加入。或者我可以使用以下查询 Select * from a join b On (a.id is not null and a.id=b.id or a.id is null) and (a.name is not null and a.name=b .name 或 a.name 为空)和(a.city 不为空且 a.city=b.city 或 a.city 为空)
-
也许我没有正确理解它,但请在表格中添加更多示例数据,然后在此基础上给出您的预期输出。使用sqlfiddle 创建它并分享链接,以便我们看到你做了。
-
表达式
a.id is not null and a.id=b.id与a.id = b.id相同,因为=运算符无论如何都不会比较空值。a.id is null似乎表明您想要外部连接。根据您的样本数据,预期的输出是什么。请添加带有a.id = null的示例行,并显示这些行的结果应该是什么。 -
基本上我不想在表a中整列为空时加入该列