[英]How do I select rows where a column contains
here is the field in my table 这是我表中的字段
how do I select rows where a column contains only 5, not 15 if SELECT * FROM
vendor WHERE
services LIKE '%5%'
it will select that have 15 too. 我如何选择列仅包含5的行,如果SELECT * FROM
供应商WHERE
服务LIKE '%5%'
那么它将选择15的行。 any idea? 任何想法?
As other comments noted, normalize your database. 如其他注释所述,对数据库进行规范化。 But, here's a hack to get what you're looking for temporarily: 但是,这是一种临时获取您所寻找内容的技巧:
select * from vendor where ',' + services + ',' like '%,5,%'
select * from vendor where services = '5' OR services LIKE '5,%' OR services like '%,5' OR services LIKE '%,5,%' 从供应商处选择*服务='5'或服务类似'5,%'或服务类似'%,5'或服务类似'%,5,%'
But seriously normalize the DB 但是认真规范数据库
You can use regexp
: 您可以使用regexp
:
select * from my_table
where
my_col regexp '^5$' or
my_col regexp ',5$' or
my_col regexp ',5,';
Haven't tried the above expression myself, but something like that would work. 我自己还没有尝试过上面的表达式,但是类似的方法会起作用。
EDIT: with one regexp: 编辑:与一个正则表达式:
select * from my_table
where
my_col regexp '^5$|,5$|,5,'
Actually MySQL provides a FIND_IN_SET
function for such comma-separated strings. 实际上,MySQL为此类逗号分隔的字符串提供了FIND_IN_SET
函数 。 This is simpler and cleaner than complex like
or regexp solutions: 这比复杂的like
或正则表达式解决方案更简单,更干净:
mysql> select * from vendor where find_in_set('5', services) > 0;
+----+----------+
| id | services |
+----+----------+
| 1 | 5 |
| 3 | 9,5 |
+----+----------+
2 rows in set (0.00 sec)
But still beware - such design could result in low performance. 但请注意-这样的设计可能会导致性能降低。
Using regexp: 使用正则表达式:
SELECT * FROM `VENDOR` WHERE `services` REGEXP '[[:<:]]5[[:>:]]';
(I just recently answered this in Match tags in MYSQL ) (我最近在MYSQL的Match标签中回答了这个问题)
where
条件允许的情况下,您可以编写services='5' or services like '%,5' or services like '%,5,%' or services like '5,%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.