2011-01-13 130 views
0

我在一列中存储了用逗号分隔的类别ID列表:Mysql的使用IN

像这样:1,2,3,4,5,6,7,8 ..等等在,只是他们的ID。

然后,我正在执行查询以获取所有具有ID 2,3类别的行,并且它在包列表中包含少量项目时起作用。

这是查询和表:

mysql> select * from packages where category_id IN (2,3); 

的任何解决方案,以获取包含ctegory ID包的完整列表2或3

回答

0

这应该回答你的问题:

select * from packages where category_id LIKE "2" or category_id LIKE "3";

但是,您最好将数据非规格化。

0

坏主意去正常化

您应该标准化数据

一本

mysql> create table the_in (expr varchar(255)); 
Query OK, 0 rows affected (0.00 sec) 

mysql> insert into the_in values('1,2'); 
Query OK, 1 row affected (0.00 sec) 

mysql> create table some_table (id int(10)); 
Query OK, 0 rows affected (0.00 sec) 

mysql> insert into some_table values (1), (2), (3), (4); 
Query OK, 4 rows affected (0.00 sec) 
Records: 4 Duplicates: 0 Warnings: 0 

mysql> select * from some_table 
where find_in_set(id, (select expr from the_in)); 
+------+ 
| id | 
+------+ 
| 1 | 
| 2 | 
+------+ 
2 rows in set (0.00 sec)

find_in_set可能的解决方案 - 谨防性能