run in this way,   no why,   only for you heart
CSDN博客(点击进入) CSDN
51CTO(点击进入) 51CTO

表连接查询 条件在On与Where后区别

表连接条件放在 On 和 Where 后面有什么区别吗?


答案是有区别的,所有的连接条件都必需要放在ON后面,不然前面的所有LEFT,和RIGHT关联将作为摆设,而不起任何作用。

下面用两张表people和scores,people表的Id关联scores表的pid证明下:
在这里插入图片描述
1. LEFT JOIN 测试
    1.1条件在On后:

  SELECT 
	  s.*,
	  p.*
  FROM [test].[dbo].[scores] s
  Left JOIN [test].[dbo].[people] p ON 1=1 AND s.pid=p.id

在这里插入图片描述
    1.2条件在Where后:

  SELECT 
	  s.*,
	  p.*
  FROM [test].[dbo].[scores] s
  Left JOIN [test].[dbo].[people] p ON 1=1
  Where s.pid=p.id

在这里插入图片描述
    1.3 区别:
     可以看到:表连接条件放在Where后面,LEFT JOIN的作用失效。

2. Right JOIN 测试
    2.1条件在On后:

  SELECT 
	  s.*,
	  p.*
  FROM [test].[dbo].[scores] s
  Right JOIN [test].[dbo].[people] p ON 1=1 AND s.pid=p.id

在这里插入图片描述
    2.2条件在Where后:

  SELECT 
	  s.*,
	  p.*
  FROM [test].[dbo].[scores] s
  Right JOIN [test].[dbo].[people] p ON 1=1 
  Where s.pid=p.id

在这里插入图片描述
    2.3 区别:
     可以看到:表连接条件放在Where后面,Right JOIN的作用失效。

3.总结:
     所有的连接条件都必需要放在ON后面,不然前面的所有LEFT,和RIGHT关联将作为摆设,而不起任何作用。

posted @ 2019-05-05 23:43  _小龙人  阅读(237)  评论(0编辑  收藏  举报