在這個例子中,我將創建一個表,用隨機數加載它,並且在提供的列表中搜索每個號碼。這裏有一個問題:提供的列表必須以逗號開頭並以逗號結尾。
從你的問題,我會用 '-3,2,5-,'
這裏是例子
use test
drop table if exists notforeverdata;
create table notforeverdata
(
id int not null auto_increment,
num VARCHAR(255),
PRIMARY KEY (id)
);
insert into notforeverdata (num) values
(2),(7),(9),(11),(13),(15),(4),(3),(90),(97),(18),(5),(17);
SELECT * FROM notforeverdata;
SELECT * FROM notforeverdata WHERE LOCATE(CONCAT(',',num,','),(',3,2,5,'));
我居然跑它在MySQL 5.5.12我的桌面上。結果如下:
mysql> use test
drop table if exists notforeverdata;
Database changed
mysql> drop table if exists notforeverdata;
Query OK, 0 rows affected (0.03 sec)
mysql> create table notforeverdata
-> (
-> id int not null auto_increment,
-> num VARCHAR(255),
-> PRIMARY KEY (id)
->);
Query OK, 0 rows affected (0.12 sec)
mysql> insert into notforeverdata (num) values
-> (2),(7),(9),(11),(13),(15),(4),(3),(90),(97),(18),(5),(17);
Query OK, 13 rows affected (0.06 sec)
Records: 13 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM notforeverdata;
+----+------+
| id | num |
+----+------+
| 1 | 2 |
| 2 | 7 |
| 3 | 9 |
| 4 | 11 |
| 5 | 13 |
| 6 | 15 |
| 7 | 4 |
| 8 | 3 |
| 9 | 90 |
| 10 | 97 |
| 11 | 18 |
| 12 | 5 |
| 13 | 17 |
+----+------+
13 rows in set (0.00 sec)
mysql> SELECT * FROM notforeverdata WHERE LOCATE(CONCAT(',',num,','),(',3,2,5,'));
+----+------+
| id | num |
+----+------+
| 1 | 2 |
| 8 | 3 |
| 12 | 5 |
+----+------+
3 rows in set (0.00 sec)
mysql>
這當然會執行全表掃描。儘管如此,這是有效的。
試試吧!
切勿在數據庫中使用CSV。 – Johan
有['FIND_IN_SET'](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set)函數,也許它可以幫助你 – knittl