bik*_*y77 80 mysql sql database
我的表中有一个字段COLORS (varchar(50)),SHIRTS其中包含逗号分隔的字符串,例如1,2,5,12,15,.每个数字代表可用的颜色.
当运行查询select * from shirts where colors like '%1%'以获得所有红色衬衫(颜色= 1)时,我还得到颜色为灰色(= 12)和橙色(= 15)的衬衫.
我应该如何重写查询,以便仅选择颜色1而不是所有包含数字1的颜色?
And*_*mar 174
经典的方法是在左侧和右侧添加逗号:
select * from shirts where CONCAT(',', colors, ',') like '%,1,%'
Run Code Online (Sandbox Code Playgroud)
但是find_in_set也有效:
select * from shirts where find_in_set('1',colors) <> 0
Run Code Online (Sandbox Code Playgroud)
Sha*_*ngh 29
在这种情况下,FIND_IN_SET是你的朋友
select * from shirts where FIND_IN_SET(1,colors)
Run Code Online (Sandbox Code Playgroud)
Joe*_*lli 23
看一下MySQL 的FIND_IN_SET函数.
SELECT *
FROM shirts
WHERE FIND_IN_SET('1',colors) > 0
Run Code Online (Sandbox Code Playgroud)
Rol*_*DBA 11
这肯定会起作用,我实际上尝试过:
lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)
lwdba@localhost (DB test) :: CREATE TABLE shirts
-> (<BR>
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ticketnumber INT,
-> colors VARCHAR(30)
-> );<BR>
Query OK, 0 rows affected (0.19 sec)
lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
-> (32423,'1,2,5,12,15'),
-> (32424,'1,5,12,15,30'),
-> (32425,'2,5,11,15,28'),
-> (32426,'1,2,7,12,15'),
-> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors |
+----+--------------+--------------+
| 1 | 32423 | 1,2,5,12,15 |
| 2 | 32424 | 1,5,12,15,30 |
| 4 | 32426 | 1,2,7,12,15 |
+----+--------------+--------------+
3 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
试试看 !!!
如果颜色集或多或少是固定的,那么最有效且最易读的方法是在应用程序中使用字符串常量,然后在查询中使用MySQL的SET类型FIND_IN_SET('red',colors).当使用SET带有FIND_IN_SET的类型时,MySQL使用一个整数来存储所有值,并使用二进制"and"操作来检查值的存在,这比扫描以逗号分隔的字符串更有效.
In SET('red','blue','green'),'red'将在内部存储1,'blue'将在内部存储,2并'green'在内部存储为4.该值'red,blue'将被存储为3(1|2)和'red,green'作为5(1|4).
| 归档时间: |
|
| 查看次数: |
126811 次 |
| 最近记录: |