mysql in操作 MySQL查詢in操作排序

2021-10-25 14:57:40 字數 2605 閱讀 6583

in操作排序

先說解決方案:

select * from test where id in(3,1,5) order by field(id,3,1,5);

或許有人會注意過,但我以前真不知道

sql: select * from table where id in (3,6,9,1,2,5,8,7);

這樣的情況取出來後,其實,id還是按1,2,3,4,5,6,7,8,9,排序的,但如果我們真要按in裡面的順序排序怎麼辦?sql能不能完成?是否需要取回來後再foreach一下?其實mysql就有這個方法

sql: select * from table where id in (3,6,9,1,2,5,8,7) order by field(id,3,6,9,1,2,5,8,7);

出來的順序就是指定的順序了。。。。這個,以前還真的從來沒用過,偶爾看到,所以就記錄了一下。一是做個筆記,二是希望可以給更多的人看到

mysql中not in語句對null值的處理

mysql> select count(name) from cve where name not in ('cve-1999-0001', 'cve-1999-0002');

| count(name) |

| 17629 |

1 row in set (0.02 sec)

mysql> select count(name) from cve where name not in ('cve-1999-0001', 'cve-1999-0002', null);

| count(name) |

| 0 |

1 row in set (0.01 sec)

當在子查詢**現null的時候,結果就一定是0了。查了一下手冊,確實有這樣的說法。所以最後實際採用了這樣的查詢:

select count(distinct name)

from cve

where name not in (select cveid from cve_sig where cveid is not null)

順便提一下mysql中正規表示式匹配的簡單使用:

select count(alarmid)

from alarm

where (cve not rlike '^cve-[0-9]-[0-9]$' or cve is null)

當然,rlike也可以寫作regexp,我個人傾向於使用rlike,因為拼寫接近like,可以見名知義。

mysql - not in

table:info primary key(id, info_type_id)

id, info_type_id, programme_id, episode_id

3, 4, 382, 100034

3, 8, 382, 100034

4, 8, 382, 100034

6, 8, 382, 100034

7, 8, 382, 100034

8, 8, 382, 100034

9, 8, 382, 100034

10, 8, 382, 100034

11, 8, 382, 100034

12, 8, 382, 100034

13, 8, 382, 100034

100001, 4, 382, 100034

100002, 4, 382, 100034

排除(id=3 && info_type_id=8) and (id=4 && info_type_id=8)這兩條記錄,即找出其它記錄

error: select * from info where episode_id=100034 and id not in(3,4) and info_type_id not in (8);

error result:

id, info_type_id, programme_id, episode_id

100001, 4, 382, 100034

100002, 4, 382, 100034

correct: select * from info where episode_id=100034 and (id<>3 or info_type_id<>8) and (id<>4 or info_type_id<>8);

correct result:

id, info_type_id, programme_id, episode_id

3, 4, 382, 100034

6, 8, 382, 100034

7, 8, 382, 100034

8, 8, 382, 100034

9, 8, 382, 100034

10, 8, 382, 100034

11, 8, 382, 100034

12, 8, 382, 100034

13, 8, 382, 100034

100001, 4, 382, 100034

100002, 4, 382, 100034

理解:id<>3 or info_type_id<>8排除掉id=3 && info_type_id=8這條記錄,當表中主鍵多於乙個時,不能簡單地使用key1 not in (……) and key2 not in (……)

mysql in操作和find in set函式

當我們要查詢id為1,2,3,4的資料的時候,可以用 in操作,例如 1 select from table where id in 1,2,3,4 view code 這時我有另外乙個表裡面的字段為a,儲存的值為1,2,3,4,把它作為條件去查詢的時候,那麼語句就變成了 1 select from...

MySQL 增刪改查操作

toc 登入資料庫 mysql u root p123456 建立資料庫 creat database test 檢視所有資料庫 show databases 檢視資料庫中所有的資料表 show tables 選中資料庫 usedatabases 建立資料表 create table pet nam...

MySQL增刪改查操作

增刪改查操作 查詢表中的所有的記錄 select from 表名 xs 建立資料庫 create database if not exists xsgl 8.2建立表 cerate table if not exists 判斷是否存在 表名 xsb 8.3刪除 drop database if ex...