简体   繁体   English

更好的mysql选择Query来过滤数据(PHP)

[英]Better mysql select Query to filter data (PHP)

I am having a problem where i want to search data from my mysql database , this is how it goes i have a search field where a user enters location name and then i search for that location in my database and display the username based on searched location but i have some users which have more than one location in the database separated with a "comma" so my select query is not able to find, this is how my database looks 我有一个问题,我想从我的mysql数据库中搜索数据,这是怎么回事我有一个搜索字段,用户输入位置名称,然后我在我的数据库中搜索该位置,并显示基于搜索位置的用户名但我有一些用户在数据库中有多个位置用“逗号”分隔,所以我的选择查询无法找到,这就是我的数据库看起来的样子

 table name :- users 

 username ||  location

 john    ||  KIS,ITS

 alex   || KIS

So when someone is searching for KIS it is only showing alex name not john's though he is a part of KIS aswell , i am wondering if there is any better query that can solve my problem 所以,当有人正在搜索KIS时,它只显示亚历克斯名称而不是约翰的,虽然他也是KIS的一部分,我想知道是否有更好的查询可以解决我的问题

Thanks 谢谢

Updated query for new question requirements 更新了新问题要求的查询

Works for 效劳于

KIS KIS

KIS,(anything) at start KIS,(任何事情)一开始

(anything),KIS,(anything) at middle (任何东西),KIS,(任何东西)在中间

(anything),KIS at last (任何事情),KIS终于来了

Query 询问

SELECT * 
FROM users
WHERE location = 'KIS' OR LIKE 'KIS,%' OR LIKE '%,KIS,%' OR LIKE '%,KIS' 

If you need to find a part of input string you could use 如果您需要找到可以使用的输入字符串的一部分

SELECT * FROM users WHERE location LIKE '%KIS%'

If you need to get correct input you can use 如果您需要获得正确的输入,您可以使用

SELECT * FROM users
WHERE FIND_IN_SET(LOWER('KIS'), LOWER(location)) > 0
select username from users where location like '%KIS%'

Use regular expressions. 使用正则表达式。

SELECT * FROM users WHERE location RLIKE '(^|[^_alnum])KIS($|[^_alnum])'

Or if your data is always separated by one comma, then use this: 或者,如果您的数据始终以逗号分隔,请使用以下命令:

SELECT * FROM users WHERE location RLIKE '(^|,)KIS($|,)'

But know that your database is not in 1st normal form, and storing complex data, and looking it up is going to greatly affect performance. 但是要知道你的数据库不是第一种正常形式,并且存储复杂数据,查找它会对性能产生很大影响。 If it's possible use a separate table to store the location for each user. 如果可以使用单独的表来存储每个用户的位置。

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

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