![](/img/trans.png)
[英]How to concat find_in_set results with comma separated string in mysql
[英]MySQL Query - Find_in_set on comma separated columns
我在進行事件數據庫的查詢時遇到查詢問題。 目的是關於運動,其結構是:
id_event event_sport event_city
1 10 153
2 12 270
3 09 135
桌上運動就像:
sport_id sport_name
1 Basketball
表格城市為:
city_id city_name
1 NYC
事情變得復雜了,因為我的事件表如下:
id_event event_sport event_city
1 10,12 153,270
2 7,14 135,271
3 8,12 143,80
而且我有一個多輸入搜索表單,以便人們可以在自己的城市中搜索多個體育項目或多個城市的活動。 我正在使用選擇
例如,來自“選擇”的搜索結果是:
City = 153,270 (if user selected more than one city)
Sport = 12 (if user only selected one sport, can be "9,15")
因此,我需要在同一列中搜索城市和體育的多個值,並用逗號分隔,並且知道有時候,如果用戶輸入的值不多,我們只能搜索一個值。
我當前的查詢是:
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)
;
搜索一個城市很好,但是如果用戶搜索兩個或多個城市,我將無法顯示它。
你能幫我么?
提前致謝。
當用戶輸入多個城市和/或運動時,請以逗號分隔,然后查詢應類似於:
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 ...)
使用PHP,您可以使用以下命令構建這些OR
表達式:
$city_list = implode(' OR ', array_map(function($x) { return "FIND_IN_SET('$x', e.event_city)"; }, explode(',', $_POST['cities'])));
進行同樣的操作以制作$ sport_list,然后您的SQL字符串將包含:
WHERE ($city_list) AND ($sport_list)
如您所見,這確實很復雜並且效率很低,我建議您按照注釋中的建議規范化架構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.