資料分析師 02 SQL MySQL 020

2021-10-12 11:08:21 字數 1939 閱讀 7527

手動反爬:mysql的高階聯結表(where…in…,left join…on…,count…where…group by)

注:以下使用 mysql 演示

假設有兩張表:

a表包含作為 pk的 id

b表包含作為 fk的 id

此時 a表的 pk id應該以 1:∞ 的形式與 b表的 fk id對應。

在傳統的資料庫中,這種方式成為 norm正規化連線。

而且這樣的表要加入 constra約束條件(比如:當 a表中存在 id為3的客戶,此客戶的資訊才能在 b表**現)

而現在大部分的資料庫為了應對 半結構化 的模式,取消了 constra約束條件,只要用 「=」 就可以進行連線。

找出 products表中 vend_id為 1003的資料:

select

*from products where vend_id =

'1003'

;

自聯結方式很少在日常應用**現

舉個使用場景的栗子:

當表中的資料報含了多個層級結構時,找出對應的級次關係(比如:高層領導 - 多個中層領導 - 多個員工)

方法1:

(注意:這裡用了in而不是=

select

*from products where prod_id in

(# 注意!

select prod_id from products where vend_id =

'1003'

);

方法2:

select p1.prod_id, p1.prod_name from products p1, products p2

where p1.prod_id = p2.prod_id

and p2.vend_id=

'1003'

;

select p1.prod_id, p1.prod_name from products p1, products p2

where p2.vend_id =

'1003'

;

方法1:

select

*from customers c ,orders o

where c.cust_id = o.cust_id ;

方法2:

(注意:這裡用的是left join ... on ...用的是on

select

*from customers c left

join orders o

on c.cust_id = o.cust_id ;

select c.cust_name, c.cust_id,

count(*

)from customers c, orders o

where c.cust_id = o.cust_id

group

by c.cust_id ;

select c.cust_name, c.cust_id,

count(*

)from customers c left

join orders o

on c.cust_id = o.cust_id

group

by c.cust_id ;

資料分析師 02 SQL MySQL 009

toc 手動反爬 mysql的資料排序 order by 注 以下使用 mysql 演示 懶得看的看這裡,彙總 1 單字段排序 select prod name,prod price from products order by prod price 公升序 select prod name,pro...

資料分析師 02 SQL MySQL 010

手動反爬 mysql的資料過濾01 select,where,between 注 以下使用 mysql 演示 where子句的操作符包括 篩選 小於10元的資料 select prod name,prod price from products where prod price 2.5 篩選 商編號...

資料分析師 02 SQL MySQL 013

手動反爬 mysql中的正規表示式 regexp 注 以下使用 mysql 演示 正規表示式 re 是用來匹配文字的特殊的串 字元集合 正規表示式的作用是匹配文字,將乙個模式 正規表示式 與乙個文字串進行比較。mysql用where子句對正規表示式提供了初步的支援,允許指定正規表示式,過濾selec...