MySql中多表聯查是要注意的事項
1.簡單介紹一下多表聯查的概念
當要查詢的資料在多張表時,使用多表聯查
2.多表聯查的分類
MySQL聯合查詢
交叉聯合查詢 cross join
內連線聯合查詢 inner join (MySQL簡寫join)
外連線聯合查詢: 左外連線聯合查詢 left outer join (MySQL簡寫left join)
右外連線聯合查詢 right outer join (MySQL簡寫right join)
3.建立兩張表
create table table1( customer_id varchar(20) not null, city varchar(20) not null, primary key(customer_id) ) default charset = utf8 #---------------------------------------------------------------- create table table2( order_id int not null auto_increment, customer_id varchar(20), primary key(order_id) )default charset = utf8 #----------------------------------------------------------------------- insert into table1(customer_id,city) values ('tedu','hangzhou'),('jd','shanghai'),('tx','hangzhou'),('baidu','hangzhou') insert into table2(customer_id) values ('tedu'),('tedu'),('jd'),('jd'),('jd'),('tx'),(Null)
4.具體的介紹
1 cross join 效果
select * from table1 cross join table2
得到一張很大的資料表(28條資料記錄 4*7)
這樣的資料表稱為兩張資料表的笛卡爾積
2 inner join 效果【分為有條件的內連線和無條件的內連線】
select * from table1 inner join table2
其效果與cross join是一樣的
得到一張很大的資料表(28條資料記錄 4*7)
這樣的資料表稱為兩張資料表的笛卡爾積
3 left outer join效果
不能直接讓兩張表進行左外連線
select * from table1 left join table2
左外連線是在內連線基礎上進行的
首先讓兩張表先做“有條件”的內連線。
條件就是兩張表要有共同列,在共同列上做內連線
然後才能進行左外連線。
有條件的內連線
select * from table1 join table2 on
table1.customer_id = table2.customer_id
在有條件的內連線的基礎上做左外連結
select * from table1 left join table2 on
table1.customer_id = table2.customer_id
4 right outer join效果
不能直接讓兩張表進行右外連線
select * from table1 right join table2
右外連線是在內連線基礎上進行的
首先讓兩張表先做“有條件”的內連線。
條件就是兩張表要有共同列,在共同列上做內連線
然後才能進行右外連線。
select * from table1 join table2 on
table1.customer_id = table2.customer_id
select * from table1 right join table2 on
table1.customer_id = table2.customer_id