如何为sql连接选择合适的过滤器

时间:2014-06-12 14:24:10

标签: sql

如果我有表A和表B,每个表都有一列:

A:
col1
1
2
3
1

B:
col1
1
1
4

并且我想要来自A的所有行和来自B的匹配行,只有当列在两个表中都具有非空值时,我应该使用哪一行?

select * from A left join B on A.col1 = B.col1 and A.col1 is not null AND B.col1 is not null;

select * from A left join B on A.col1 = B.col1 where A.col1 is not null OR B.col1 is not null;

select * from A left join B on A.col1 = B.col1 and (A.col1 is not null OR B.col1 is not null;)

我的猜测是第一个和第三个是相同的,并将提供所需的输出。

4 个答案:

答案 0 :(得分:2)

如果要跳过空值并且只想在现有值上链接两个表,则应使用INNER JOIN,空检查是多余的:

SELECT A.* 
FROM A INNER JOIN B ON A.col1 = B.col1  

NULL永远不会匹配任何其他值(甚至不是NULL本身),除非连接条件明确使用IS NULLIS NOT NULL谓词。

答案 1 :(得分:1)

在一条评论中,你说在这种情况下你检查的不仅仅是空值,我可能会采用衍生的表格或CTE方法。下面显示的Dervied表没有指定哪个数据库后端,所以我不知道你是否可以使用CTE。

选择 从 (从testa中选择test不为null或test<>''或test<>'N / A')a 加入 (从testb中选择test不为null或test<>''或test<>'N / A')b     ON a.col1 = b.col1

答案 2 :(得分:0)

由于你想要来自A的所有行,下面的查询应该可以工作:

select * from A left outer join B on A.col1 = B.col1 where A.col1 is not null and A.col1<>'N/A' and A.col1<>''

http://sqlfiddle.com/#!2/98501/14

答案 3 :(得分:0)

你只需要

select * from A left join B on A.col1 = B.col1

NULL永远不会匹配任何东西(当不与IS NULL等比较时),因此A中的NULL将不匹配B中的任何内容。