A加油卡表:
id, userName, cardNo
1 aaa 111
2 bbb 111
3 aaa 222
B加油記錄表:
id, number, userName , cardNo,
1 1234 aaa 111
2 234 bbb 111
left join:
select * from B b left join A a on a.userName = b.userName where b.userName=aaa
由于上面sql中,on后面的條件,userName在A表中對應多條,而不是對應一條,結果集就是笛卡爾積。B表中的1條滿足剩余A表中的2條滿足。結果為2條。
select * from B b left join A a on a.userName = b.userName and a.cardNo = b.cardNo where b.userName=aaa
由于上面sql中,on后面的兩個條件在A表中只能找到一條唯一數據,所以結果就是B表中有多少條數據滿足where,結果集就返回多少條數據。這里是返回一條數據
right join:
下面這個sql與上面的left join效果一樣:
select * from A a right join B b on a.userName = b.userName and a.cardNo = b.cardNo where b.userName=aaa
inner join:
select * from A a inner join B b on a.userName = b.userName and a.cardNo = b.cardNo where a.userName=aaa
還是首先看on后面的條件,如果A表中的一條數據對應on的兩個條件在B中只有一條數據,則返回滿足where條件的2條數據。
select * from B b inner join A a on a.userName = b.userName and a.cardNo = b.cardNo where a.userName=aaa
以上總結一條:看on后面的條件,在被關聯表中的數據是一條還是多條。
更多相關問題請訪問:MySQL視頻教程
以上就是mysql的left join、right join、inner join的詳細內容,更多請關注其它相關文章!