資料分析師 02 SQL MySQL 013

2021-10-12 10:23:03 字數 2334 閱讀 4916

手動反爬:mysql中的正規表示式(regexp)

注:以下使用 mysql 演示

正規表示式(re)是用來匹配文字的特殊的串(字元集合)。

正規表示式的作用是匹配文字,將乙個模式(正規表示式)與乙個文字串進行比較。

mysql用where子句對正規表示式提供了初步的支援,允許指定正規表示式,過濾select檢索出的資料。

(學過網路爬蟲的小夥伴們應該對re已經很熟悉了,大概看看就好)

先把本文中用到的幾個資料庫內容po上來

這個是products表:

不使用re,和使用re(找prod_name中包含 「1000」 的資料):

select prod_name from products

where prod_name like

'%1000'

;# 這樣匹配的話,資料量在10萬條以上時,效率低下

select prod_name from products

where prod_name regexp

'1000'

;# 只要包含了1000的,都會匹配出來

用re找prod_name中包含 「000」 的資料:

select prod_name from products

where prod_name regexp

'.000'

;# 正則中 "." 代表任意乙個字元

select prod_name from products

where prod_name regexp

'1000|2000'

;# "|"代表or

代表的是乙個字元,以下的[123]代表的是 「1或2或3」

select prod_name from products

where prod_name regexp

'[123] ton'

;

代表的是乙個字元,以下的[1-5]代表的是 「1至5中任意乙個字元」

還可以寫成:[0-9]或者[a-za-z]之類的

select prod_name from products

where prod_name regexp

'[1-5] ton'

;

^345表示 「不包含3、4、5」

select prod_name from products

where prod_name regexp

'[^345] ton'

;

由於re中某些標點符號已經有了特定的含義,所以就用\\符號對其進行轉義,讓這個符號代表它本身。(我不知道該怎麼寫,差不多得了,往下看)

查詢名字中包含 「.」 的資料:

select prod_name from products

where prod_name regexp

'\\.'

;# 這個時候 「.」 才代表它自己,而不是代表任意字元

類似的還有:

用 re 找到第二條,而非第一條:

select prod_name from products

where prod_name regexp

'\\([0-9] sticks?\\)'

;

以下三條查詢**執行的效果是一樣的(代表前面的內容重複n次):

select prod_name from products

where prod_name regexp

'[0-9][0-9][0-9][0-9]'

;select prod_name from products

where prod_name regexp

'[0-9]'

;select prod_name from products

where prod_name regexp

'[[:digit:]]'

;

資料分析師 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 020

手動反爬 mysql的高階聯結表 where in left join on count where group by 注 以下使用 mysql 演示 假設有兩張表 a表包含作為 pk的 id b表包含作為 fk的 id 此時 a表的 pk id應該以 1 的形式與 b表的 fk id對應。在傳統的...