sql 表連接on后面加where和and的區別


測試數據


create table testA( Id number(10) primary key, Name varchar(10) ) insert into testA values(1,'小黃'); insert into testA values(2,'小綠'); insert into testA values(3,'小白'); insert into testA values(4,'小黑'); insert into testA values(5,'小花'); commit create table testB( Id number(10) primary key, age number(10) ) insert into testB values(1,10); insert into testB values(2,11); insert into testB values(3,12); insert into testB values(4,13); commit 

on后面加and


select * from testA a left join testB b on a.id = b.id and b.age=10 
  • 1
  • 2

在這里插入圖片描述

on后面加where

select * from testA a left join testB b on a.id = b.id where b.age=10 
  • 1

在這里插入圖片描述

on 是用於消除笛卡兒積的,表連接時不加on會報錯,left join語句會從左表那里返回所有的行,即使在右表中沒有匹配的行,on后面接and也會兼顧左連接,不管and 后面接什么內容,左表數據都會全部展示
下圖語句由於a.name =10在testA沒有匹配數據,所以與其關聯的testB也匹配不到數據。

select * from testA a left join testB b on a.id = b.id and a.name='10' 
  • 1

在這里插入圖片描述
使用where就是對連接后的結果集進行條件篩選

select * from testA a left join testB b on a.id = b.id where a.name='10' 
  • 1

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM