简体   繁体   English

MYSQL搜索带有逗号分隔值的单元格

[英]MYSQL search through cells with comma separated values

I am building an AJAX call which passes an array of variables (ids) through to a function which will then query a database to return rows if this ids exist in their 'catid' cell. 我正在构建一个AJAX调用,该调用将变量(id)数组传递给一个函数,如果该id在其“ catid”单元格中存在,则该查询将查询数据库以返回行。

I know how to use an array to use an 'IN' MYSQL command but in this instance there are multiple ids stored in a cell for rows, seperated by a comma. 我知道如何使用数组来使用“ IN” MYSQL命令,但是在这种情况下,单元格中存储了多个ID(以逗号分隔)。 This is stored as a varchar. 这被存储为varchar。 Is there any way I can loop through the individual ids stored in a rows categories cell? 有什么办法可以遍历存储在行类别单元格中的各个ID?

Here is a screenshot of an example row from the database. 这是数据库中示例行的屏幕截图。 I have highlighted the 'catid' cell for rows. 我已突出显示行的“ catid”单元格。 As you can see, a row can be part of many categories, with these category id's seperated by a comma)... 如您所见,行可以是许多类别的一部分,这些类别ID以逗号分隔)...

在此处输入图片说明

This is a sign of bad DB design you should first look into Database Normalization and if you can change the structure then first normalize it by using a junction table ,As of now you can use FIND_IN_SET() to find your corresponding record id in your comma separated ids column 这表明数据库设计不良,您应该首先查看数据库规范化 ,如果可以更改结构,然后首先使用联结表对其进行规范化,到目前为止,您可以使用FIND_IN_SET()在逗号中查找对应的记录ID。分隔的ID列

SELECT * FROM table 
WHERE  FIND_IN_SET('id1',column) > 0
AND FIND_IN_SET('id2',column) > 0
AND FIND_IN_SET('id3',column) > 0

Change the operator as per your wish i have shown example with AND operator,note you need to use FIND_IN_SET as many times as the no of ids you have in your array that you need to compare with your column 根据您的意愿更改运算符,我已在AND运算符示例中显示,请注意,您需要使用FIND_IN_SET次数与需要与列进行比较的数组中的ID FIND_IN_SET一样多

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

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