[英]MySQL check if value exist in row, separated by minus
I have a table with ProductIDs and associated Accessories Ids separated by minus. 我有一个表格,其中包含产品ID和相关的附件ID,中间用负号分隔。
ProductId Accessories
1 1-2-3-
2 3-4-
3 1-2-3-
4 2-3-
How can I get ProductIds where Accessories Id = 2 如何获得附件ID = 2的ProductIds
I tried this query but it is not working correct 我尝试了此查询,但无法正常工作
SELECT *
FROM `products`
WHERE '-' + Accessories + '-' LIKE '%-2-%'
LIMIT 0 , 30
Database can't be changed. 数据库无法更改。
If you absolutely have to do this incredibly bad practise that will complicate your coding life until the day you retire: 如果您绝对必须这样做,那么非常糟糕的做法会使您的编码工作复杂化,直到退休之日:
SELECT *
FROM products
WHERE CONCAT('-',Accessories) LIKE '%-2-%'
LIMIT 0 , 30
Although the following solution also has problems with using an index, I wanted to add it for completeness: 尽管以下解决方案在使用索引方面也存在问题,但我还是想添加它以确保完整性:
SELECT *
FROM `products`
WHERE find_in_set('2', replace(`accessories`, '-', ','))
LIMIT 0, 30;
Explanation: 说明:
replace(accessories, '-', ',')
turns the accessories lists into a comma separated list, for example 1-2-3-
will be converted to 1,2,3,
replace(accessories, '-', ',')
将附件列表转换为逗号分隔的列表,例如1-2-3-
将转换为1,2,3,
find_in_set(value, set)
can then be used to see if a value
is contained in set
. 然后可以使用
find_in_set(value, set)
来查看set
是否包含value
。
As I said earlier, no index can be used, but the performance should be measured on the live data set. 就像我之前说的,不能使用任何索引,但是应该根据实时数据集来衡量性能。
I think you almost had it. 我想您几乎已经拥有了。 Try this instead:
尝试以下方法:
SELECT *
FROM products
WHERE Accessories LIKE '%-2-%'
LIMIT 0 , 30
Assuming that those values ALWAYS have a trailing dash, then you've got a few cases to cover: 假设这些值总是带有一个短横线,那么您将涉及以下几种情况:
1) single value: ... WHERE Accessories = CONCAT($value, '-')
1)单值:
... WHERE Accessories = CONCAT($value, '-')
2) value at start: ... WHERE Accessories LIKE '$value-%'
2)开始时的值:
... WHERE Accessories LIKE '$value-%'
3) value in the middle: ... WHERE Accessories LIKE '%-$value-%'
3)中间值:
... WHERE Accessories LIKE '%-$value-%'
4) value at the end: ... WHERE Accessories LIKE '-$value-$'
4)最后的值:
... WHERE Accessories LIKE '-$value-$'
which'd end up being this in the full(er) SQL: 最终在完整的(er)SQL中是这样的:
SELECT ...
FROM ...
WHERE
(Accessories = CONCAT($value, '-')) OR // single
(Accessories LIKE CONCAT($value, '-%')) OR // start
(Accessories LIKE CONCAT('%-', $value, '-%')) OR // middle
(Accessories LIKE CONCAT('%-', $value, '-')) // end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.