安裝PostgreSQL之後,PostgreSQL會創建一個名爲“postgres”的用戶,創建一個名爲“postgres”的數據庫。我們就可以使用這個默認的庫做實驗。
首先建表並插入數據:
CREATE TABLE public.user(
ID SERIAL PRIMARY KEY NOT NULL,
UserID varchar(100) NOT NULL,
UserName varchar(100) NOT NULL,
PhoneNumber varchar(20) NOT NULL
);
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u1', 'tom', '123');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u2', 'Tom', '123');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u3', 'TOM', '321');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u3', 'Jane', '456');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u3', 'jane', '654');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u3', 'Janey', '789');
INSERT INTO public."user" (userid, username, phonenumber) VALUES('u3', 'janey', '987');
使用普通的like
查詢
select * from public."user" where username like '%O%';
查詢結果:
id | userid | username | phonenumber |
---|---|---|---|
3 | u3 | TOM | 321 |
使用like查詢需要%
號作爲佔位符,且PostgreSQL默認區分大小寫。
使用不區分大小寫的ilike
查詢
select * from public."user" where username ilike '%O%';
查詢結果:
id | userid | username | phonenumber |
---|---|---|---|
1 | u1 | tom | 123 |
2 | u2 | Tom | 123 |
3 | u3 | TOM | 321 |
使用不需要佔位符的~*
查詢
select * from public."user" where username ~* 'O';
查詢結果:
id | userid | username | phonenumber |
---|---|---|---|
1 | u1 | tom | 123 |
2 | u2 | Tom | 123 |
3 | u3 | TOM | 321 |
PostgreSQL正則表達式
select * from public."user" where username SIMILAR TO '%(t|j)%';
查詢結果:
id | userid | username | phonenumber |
---|---|---|---|
1 | u1 | tom | 123 |
5 | u3 | jane | 654 |
7 | u3 | janey | 987 |
總結
PostgreSQL的模糊匹配和模式查詢非常強大,這裏只是舉了幾個簡單的小例子做了一下對比。更多的用法可以訪問下面的參考鏈接瞭解。
如果感覺正則表達式還不能滿足你的要求,可以嘗試着寫一個自定義函數。
另外,由於這些查詢屬於pgsql的方言,如果要考慮以後的數據庫遷移成本的話,謹慎使用。