简体   繁体   English

以逗号分隔的列值搜索帖子数组

[英]Search post array in comma separated column value

Table - Column Data表 - 列数据

id | filter_data |
---|---------------
1  |2,3,45,67,4  |
2  |2,3,55,33,5,7|

Post variable from form as从表单发布变量为

$search_filter = {2,3,4,5}

How can I get the id which are in the search filter如何获取搜索过滤器中的id

Solution 1:解决方案1:

As @Jens commented, it's a bad DB design to store values as CSV.正如@Jens 评论的那样,将值存储为 CSV 是一种糟糕的数据库设计。 So the first solution would be to change your DB design since I don't really know what you're storing and what is the purpose of your DB/code I can't write a scheme or give any meaningful suggestion.所以第一个解决方案是改变你的数据库设计,因为我真的不知道你在存储什么以及你的数据库/代码的目的是什么我无法编写方案或给出任何有意义的建议。

Solution 2:解决方案2:

Use MySQL's find_in_set function.使用 MySQL 的find_in_set函数。

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings.如果字符串 str 在由 N 个子字符串组成的字符串列表 strlist 中,则返回 1 到 N 范围内的值。 A string list is a string composed of substrings separated by “,” characters.字符串列表是由以“,”字符分隔的子字符串组成的字符串。 If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic.如果第一个参数是一个常量字符串,第二个参数是一个 SET 类型的列,则 FIND_IN_SET() 函数被优化为使用位算术。 Returns 0 if str is not in strlist or if strlist is the empty string.如果 str 不在 strlist 中或 strlist 是空字符串,则返回 0。 Returns NULL if either argument is NULL.如果任一参数为 NULL,则返回 NULL。 This function does not work properly if the first argument contains a comma (“,”) character.如果第一个参数包含逗号 (“,”) 字符,则此函数无法正常工作。

SELECT id FROM table
WHERE FIND_IN_SET(searchFilterHere, filter_data)

Solution 3:解决方案3:

You can use the LIKE operator.您可以使用LIKE运算符。 (Some members probably will kill me for suggesting it, but if you don't want to change your DB design - this is a creative option). (有些成员可能会因为建议而杀了我,但如果你不想改变你的数据库设计 - 这是一个创造性的选择)。

Let's check the following code:让我们检查以下代码:

SELECT id FROM table WHERE filter_data LIKE '%2,%'

The problem is that it will return the id of a field with 22, in the filter_data's column.问题是它会在 filter_data 的列中返回一个22,的字段的 id。 Therefore, you'll have to change the data under that column so , will appear also as the first and last characters.因此,您必须更改该列下的数据,因此,也将显示为第一个和最后一个字符。 For instance:例如:

id | filter_data   |
---|---------------
1  |,2,3,45,67,4,  |
2  |,2,3,55,33,5,7,|

And now you can do the following:现在您可以执行以下操作:

SELECT id FROM table WHERE filter_data LIKE '%,2,%'

If you have multiple "search filters" you can combine the LIKE s with an OR operator.如果您有多个“搜索过滤器”,您可以将LIKEOR运算符结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM