Compare Value with Comma Separated String SQL PHP

风流意气都作罢 提交于 2020-01-23 18:03:30

问题


I am using two-tier chained select boxes on my webpage to filter data...I am having problem with my query for the second select values...

table:

id     name      cat                        loc

1      ABC       resort                     mall road
2      BCD       banquet hall               mall road
3      CDE       farm house, banquet hall   pakhowal road
4      DEF       hotel                      ferozpur road
5      FEZ       hotel                      fountain chowk
6      ZEX       resort                     mall road

I have two select boxes in which first one is for DISTINCT cat values...which is working perfectly for me...

Query i am using is:

select distinct cat from 
(select  trim(substring_index(substring_index (concat(cat,',,'),',',n),',',-1)) 
as cat from table t 
cross join (select 1 as n union all select 2 union all select 3) r) t 
where  cat <> '' ORDER BY cat ASC

Output:

cat

banquet hall
farm house
hotel
resort

Now I want to make an query which selects all those areas that have same cat value we select in first box like if i select "resort" from first select it chose "mall road" for second box...and in case I chose "banquet hall" then it should chose "mall road" and "pakhowal road" and so on.

I have used a query for this also but it is not working properly for me...

Second select box query:

SELECT DISTINCT loc 
from table 
WHERE cat = '$_POST[cat]' AND loc IS NOT NULL

It gives right output for "resort" and "hotel" cat only....if I chose "farm house" or "banquet hall" it doesn't fetch "pakhowal road"...

How I can change my query to achieve this... ?


回答1:


Try this:

SELECT DISTINCT loc
FROM [YourTable]
WHERE INSTR(CONCAT(', ',cat,' ,'),CONCAT(', ','$_POST[cat]',' ,'))>0 AND loc IS NOT NULL 


来源:https://stackoverflow.com/questions/40991678/compare-value-with-comma-separated-string-sql-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!