sql 聯合查詢

2021-09-30 03:15:59 字數 1111 閱讀 1649

1,內聯和外聯查詢的區別

內聯join(inner join):    

join ,把兩個表連線在一起,返回兩個表中相匹配的記錄,是兩表的交集。  

左外聯left join(left outer join):    

left join,左側表所有的記錄都返回,右側匹配的記錄返回,沒有匹配的返回null  

右外聯right join(right outer join):  

與left join相反,右側的記錄返回,左側返回匹配的記錄,沒有匹配返回null

例: [table1]   id   name

1    lee

2    zhang

4    wang

[table2]   id    score

1      90

2      100

3      70

select * from table table1 left join table2 on table1.id = table2.id的結果

id name  id score

1  lee   1   90

2  zhang 2  100

4  wang null null

select * from table table1 right join table2 on table1.id = table2.id的結果

id name  id score

1  lee   1   90

2  zhang 2  100

null null 3   70

select * from table table1 join table2 on table1.id = table2.id的結果

id name  id score

1  lee   1   90

2  zhang 2  100

2,聯合查詢效率影響的因素

是否建立了索引,可以指定特定索引 use index(key_list);

表的多少,表多了,聯表的效率會降低

表記錄的大小,一般兩表中乙個表較小,另一表較大的話就無需要聯合查詢了;

on 後判斷的字段必須為 not null;

SQL 聯合查詢

use xsgl go select from student select from cause select from exam 聯合查詢 join on 預設為inner,如果有right or left 那麼就指的是外聯,outer 可以不寫 1.最長見為內聯 table1 inner jo...

sql聯合查詢

sql查詢 多表聯合查詢 將具有相同的字段的查詢結果合併為乙個表 關鍵字 union 例項 查詢subs表 select subs id,prefix,acc nbr,cust id,user id,acct id,price plan id,area id,update date from sub...

SQL 聯合查詢

a表 aaa bbb ccc 1a 1b 1c 2a 2b 2c 3a 3b 3c b表 aaa bbb ddd 1a 1b 1d 4a 4b 4d 1 union union all all 表示將查詢的所有結果都合併到結果集中,若不加all會將重複的行只保留一行 sql view plain c...