MySQL 查詢in操作,查詢結果按in集合順序顯示
複製代碼 代碼如下:select * from test where id in(3,1,5) order by find_in_set(id,'3,1,5');
select * from test where id in(3,1,5) order by substring_index('3,1,2',id,1);
偶爾看到的。。。或許有人會注意過,但我以前真不知道
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中Regex匹配的簡單使用:
SELECT COUNT(alarmID)
FROM Alarm
WHERE (CVE NOT RLIKE '^CVE-[0-9]{4}-[0-9]{4}$' 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 (……) ..