MySQL內連接(inner join on)
MySQL的內連接使用inner join on,它的效果跟使用where是一樣的,如果聯結的是兩個表,那么需要左右的條件或者說字段是需要完全匹配的。
來看個例子:有兩張表customers客戶表和orders訂單表,外鍵是cust_id,我們需要知道哪些客戶有訂單
select customers.cust_id,orders.order_num from customers , orders where customers.cust_id = orders.cust_id;
如果我們使用內連接的話就可以這樣寫:
select customers.cust_id,orders.order_num from customers inner join orders on customers.cust_id = orders.cust_id;
但是如果我除了這些有有客戶的訂單,我還想拿到所有的訂單信息,那么怎么辦呢?
MySQL外連接(left,right)
select customers.cust_id,orders.order_num from customers right outer join orders on customers.cust_id = orders.cust_id;
外連接包含左右連接,
左連接的結果是除了匹配條件的數據還包含左邊表中的所有數據
右連接的結果是除了匹配條件的數據還包含右邊表中的所有數據
上面的那個語句的輸出結果是這樣的:
為了做個比較,我在customers表中也做了一條數據,該數據並沒有訂單信息,我們使用左連接來看下:
select customers.cust_id,orders.order_num from customers left join orders on customers.cust_id = orders.cust_id;
看下結果:
這樣應該就能很清晰看出內連接和外連接的作用了吧。
MySQL使用帶聚集函數的聯結
上面只是想知道哪些客戶有訂單,假如我們想看下每個客戶都有多少訂單呢?這就需要用到之前學過的聚集函數了
select customers.cust_name,customers.cust_id,count(orders.order_num) as counts from customers inner join orders on customers.cust_id = orders.cust_id group by customers.cust_id;
查看輸出結果:
以上就是一些高級聯結的使用。