如下两张表:
表A 表B
--- ---
F F
--- ---
A A
B B
C F
D G
E H
--- ---
WHERE:
SELECT
A.F
AS
FA, dbo.B.F
AS
FB
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F
WHERE A.F = ' A '
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F
WHERE A.F = ' A '
-----------
FA FB
-----------
A A
-----------
AND:
SELECT
A.F
AS
FA, dbo.B.F
AS
FB
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F
AND A.F = ' A '
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F
AND A.F = ' A '
------------
FA FB
------------
A A
B null
C null
D null
E null
------------
可以看出使用 WHERE 条件会筛选连接查询的结果,但不影响返回的右表字段值;
使用 AND 不会对结果进行筛选,结果一定是包含了所有的左表记录,但是会影响
返回的右表字段值,如果 ON 后面的逻辑判断返回 true 显示右表值,为 false 则显示 null。
SELECT
A.F
AS
FA, dbo.B.F
AS
FB
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F AND 1 = 1
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F AND 1 = 1
FA FB
------------
A A
B B
C null
D null
E null
------------
SELECT
A.F
AS
FA, dbo.B.F
AS
FB
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F AND 1 = 2
FROM dbo.A LEFT OUTER JOIN dbo.B ON dbo.A.F = dbo.B.F AND 1 = 2
FA FB
------------
A null
B null
C null
D null
E null
------------
如果是 INNER JOIN, WHERE 和 AND 效果相同。
SELECT
A.F
AS
FA, dbo.B.F
AS
FB
FROM dbo.A INNER JOIN dbo.B ON dbo.A.F = dbo.B.F
WHERE A.F = ' A ' / AND A.F = ' A '
FROM dbo.A INNER JOIN dbo.B ON dbo.A.F = dbo.B.F
WHERE A.F = ' A ' / AND A.F = ' A '
-----------
FA FB
-----------
A A
-----------