使用mysql和php搜索逗号分隔的值

时间:2018-09-11 09:38:57

标签: php mysql

我的表结构是

ID    NickName    City    LookingFor
------------------------------------
1      First      City1     men
2      Second     City2    Women
3      Third      City3    men,women
4      Fourth     City4    men,women

案例1:我想向正在寻找男人和女人的人展示。所需的输出应该是

ID    NickName    City    LookingFor
------------------------------------
1      First      City1     men
2      Second     City2    Women
3      Third      City3    men,women
4      Fourth     City4    men,women

情况2:我想向正在寻找男人的人展示。所需的输出应该是

ID    NickName    City    LookingFor
------------------------------------
1      First      City1     men
3      Third      City3    men,women
4      Fourth     City4    men,women

案例3:我想向正在寻找妇女的人展示。所需的输出应该是

ID    NickName    City    LookingFor
------------------------------------
1      Second     City2     women
3      Third      City3    men,women
4      Fourth     City4    men,women

我尝试使用下面的代码。但是上述所有情况并没有得到正确解决。

SELECT * FROM `table_name WHERE LookingFor LIKE  '%men,women%';

4 个答案:

答案 0 :(得分:2)

如果某人正在寻找男性和女性,则可以删除where子句,因为无论性别如何,所有记录都将被获取。

SELECT * FROM table_name

如果您要查找特定性别

SELECT *
FROM table_name
WHERE CONCAT(',', LookingFor, ',') LIKE '%,men,%';

SELECT *
FROM table_name
WHERE CONCAT(',', LookingFor, ',') LIKE '%,women,%';

答案 1 :(得分:1)

使用FIND_IN_SET函数在逗号分隔的字符串中搜索子字符串。对于您提到的各种情况,以下是适用的查询:

如果要寻找男人或女人:

SELECT * FROM table_name 
WHERE FIND_IN_SET('men', LookingFor) > 0 OR  
      FIND_IN_SET('women', LookingFor) > 0;

如果要寻找男人:

SELECT * FROM table_name 
WHERE FIND_IN_SET('men', LookingFor) > 0;

如果要寻找女性:

SELECT * FROM table_name 
WHERE FIND_IN_SET('women', LookingFor) > 0;

答案 2 :(得分:1)

我们可以在此处尝试使用FIND_IN_SET,例如该查询包含男女的城市:

SELECT *
FROM yourTable
WHERE FIND_IN_SET('men', LookingFor) > 0 AND FIND_IN_SET('women', LookingFor) > 0;

但是,将CSV数据存储在表中确实是一个坏习惯。相反,您应该标准化您的数据并为每条记录存储一种性别。

一般来说,如果LookingFor列最多只能存储两个性别,您按字母顺序排序,则可以直接检查合并的CSV值,例如

SELECT *
FROM yourTable
WHERE LookingFor = 'men,women';

答案 3 :(得分:0)

尝试以下三种情况:

SELECT * FROM table_name WHERE LookingFor LIKE  '%men%' 

SELECT * FROM table_name WHERE LookingFor LIKE  'men%' 

SELECT * FROM table_name WHERE LookingFor LIKE LookingFor LIKE  '%women%'