简体   繁体   English

使用逗号分隔的字符串搜索

[英]Search using comma separated string

So I think I completely misunderstood how FIND_IN_SET work 所以我想我完全误解了FIND_IN_SET是如何工作的

SELECT
    u.*, p.*
FROM
    users u
INNER JOIN profiles p ON p.user_id = u.id
WHERE
FIND_IN_SET('1,4,7', p.fruits)

This is not working as I thought it would. 这不符合我的想法。

1,4,7 represent the fruits selected by the user to search 1,4,7表示用户选择搜索的水果

p.fruits can look something like this 1,2,3,4,5,6,7 or 5,6,7 or 1,6,7 etc p.fruits看起来像1,2,3,4,5,6,7或5,6,7或1,6,7等

Basically I want to find the records if any of the values in the first argument match any of the values in the second argument. 基本上我想找到记录,如果第一个参数中的任何值与第二个参数中的任何值匹配。

Is this possible? 这可能吗?

if your p.fruits column is a varchar (which is not ideal for this situation, but if it is so) your query will be like 如果你的p.fruits列是一个varchar(这不适合这种情况,但如果是这样的话)你的查询就像

where …  ( concat(',', p.fruits , ‘,’) like ‘%,1,%’  
or concat(',', p.fruits , ‘,’) like ‘%,4,%’  or concat(',',p.fruits , ‘,’) like ‘%,7,%’ ) ... 

this won't be good for indexes since concatenation will disable usage of indexes .. better solution would be turn the column into a set and do the query like Michael's above .. or you can create a new table called user_fruits(fk_user_id int, fruit_id int) and create unique index on both fields and do the search in user_fruits table 这对索引不利,因为连接将禁用索引的使用。更好的解决方案是将列转换为集合并执行像Michael上面的查询..或者您可以创建一个名为user_fruits的新表(fk_user_id int,fruit_id int)并在两个字段上创建唯一索引并在user_fruits表中进行搜索

Use FIELD instead of that. 使用FIELD而不是它。

FIELD(p.fruits, 1,4,7)

You should refer to this article: 你应该参考这篇文章:

10 things in MySQL (that won't work as expected) MySQL中的10件事(不会按预期工作)

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

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