简体   繁体   English

MySQL查询-逗号分隔列上的Find_in_set

[英]MySQL Query - Find_in_set on comma separated columns

I have an issue with a Query I'm conducting to do a search on a Database of events. 我在进行事件数据库的查询时遇到查询问题。 The purpose is about sports and the structure is: 目的是关于运动,其结构是:

id_event  event_sport   event_city
   1          10           153
   2          12           270
   3          09           135

The table sports is like: 桌上运动就像:

sport_id     sport_name
   1         Basketball

and the table cities is: 表格城市为:

city_id     city_name
   1         NYC

So things get complicated, because my events table is like: 事情变得复杂了,因为我的事件表如下:

id_event  event_sport   event_city
   1         10,12       153,270
   2         7,14        135,271
   3         8,12        143,80

and I have a multi-input search form, so that people can search for events in their city for multiple sports or for multiple cities. 而且我有一个多输入搜索表单,以便人们可以在自己的城市中搜索多个体育项目或多个城市的活动。 I'm using Chosen 我正在使用选择

The search resultant from Chosen is, for example: 例如,来自“选择”的搜索结果是:

City = 153,270 (if user selected more than one city)
Sport = 12 (if user only selected one sport, can be "9,15")

So what I need is to search for multiple values on cities and sports in the same column, separated by commas, knowing that sometimes we can be searching only for one value, if user didn't input more than one. 因此,我需要在同一列中搜索城市和体育的多个值,并用逗号分隔,并且知道有时候,如果用户输入的值不多,我们只能搜索一个值。

My current query is: 我当前的查询是:

SELECT * FROM events e
LEFT JOIN cities c ON e.event_city=c.city_id
LEFT JOIN sports s ON e.event_sport=s.sport_id
WHERE FIND_IN_SET('1CITY', e.event_city) AND FIND_IN_SET('1SPORT', e.event_sport)
;

Which is good to search for one city, but if the user searches for two or more, I don't have way to show it. 搜索一个城市很好,但是如果用户搜索两个或多个城市,我将无法显示它。

Can you please help me? 你能帮我么?

Thanks in advance. 提前致谢。

When the user inputs multiple cities and/or sports, split it on commas, and then the query should look like: 当用户输入多个城市和/或运动时,请以逗号分隔,然后查询应类似于:

SELECT * FROM events e
LEFT JOIN cities c on e.event_city = c.city_id
LEFT JOIN sports s ON e.event_sport = s.sport_id
WHERE (FIND_IN_SET('$city[0]', e.event_city) OR FIND_IN_SET('$city[1]', e.event_city) OR ...)
AND (FIND_IN_SET('$sport[0]', e.event_sport) OR FIND_IN_SET('$sport[1]', e.event_sport) OR ...)

Using PHP you can build up those OR expressions with: 使用PHP,您可以使用以下命令构建这些OR表达式:

$city_list = implode(' OR ', array_map(function($x) { return "FIND_IN_SET('$x', e.event_city)"; }, explode(',', $_POST['cities'])));

Do the same to make $sport_list, and then your SQL string would contain: 进行同样的操作以制作$ sport_list,然后您的SQL字符串将包含:

WHERE ($city_list) AND ($sport_list)

As you can see, this is really convoluted and inefficient, I recommend you normalize your schema as suggested in the comments. 如您所见,这确实很复杂并且效率很低,我建议您按照注释中的建议规范化架构。

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

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