Home >Database >Mysql Tutorial >MySQL查询in操作 查询结果按in集合顺序显示

MySQL查询in操作 查询结果按in集合顺序显示

WBOY
WBOYOriginal
2016-06-07 18:03:041375browse

MySQL 查询in操作,查询结果按in集合顺序显示的实现代码,需要的朋友可以参考下。

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中正则表达式匹配的简单使用:
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 (id3 or info_type_id8) and (id4 or info_type_id8);
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
理解:id3 or info_type_id8排除掉id=3 && info_type_id=8這條記錄,當表中主鍵多于一個時,不能簡單地使用key1 NOT IN (……) AND key2 NOT IN (……) ..
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn