如何使用逗号分隔值为字段设置'where'子句?

时间:2014-05-19 06:01:45

标签: mysql

SELECT 
  ListProperty.*,PropertyType.ptype as PType,PropertyType.category as PCategoryi,locations.location as PLocation 
FROM 
  ListProperty,PropertyType,locations,ListPropertySortData 
WHERE 
  (ListProperty.ptid=PropertyType.ptid AND ListProperty.locid=locations.locid) 
  AND ListProperty.lpid IN (SELECT lpid FROM ListPropertyMore WHERE ListProperty.locid LIKE '%12,18%') 
  AND ListPropertySortData.lpid=ListProperty.lpid 
  AND expdate>=CURDATE() 
  AND status='T';

我需要输出12和18的locid

4 个答案:

答案 0 :(得分:1)

也许您可以像这样使用FIND_IN_SET

SELECT 
  ListProperty.*,
  PropertyType.ptype as PType,
  PropertyType.category as PCategoryi,
  locations.location as PLocation 
FROM 
  ListProperty,PropertyType,
  locations,
  ListPropertySortData 
WHERE 
  (
    ListProperty.ptid=PropertyType.ptid 
    AND ListProperty.locid=locations.locid
  ) 
  AND ListProperty.lpid IN 
  (
      select 
        lpid 
      from 
        ListPropertyMore 
      WHERE FIND_IN_SET (ListProperty.locid, '12,18')
  ) 
  AND ListPropertySortData.lpid=ListProperty.lpid 
  AND expdate>=CURDATE() AND status='T'

参考:

答案 1 :(得分:0)

您可以使用OR运算符。

WHERE (ListProperty.locid like '%12%' OR ListProperty.locid like '%18%') 

答案 2 :(得分:0)

对于locid 12和18,请使用GROUP BYHAVING条款:

试试这个:

SELECT PropertyType.ptype as PType,PropertyType.category as PCategoryi,locations.location as PLocation 
FROM ListProperty,PropertyType,locations,ListPropertySortData 
WHERE (ListProperty.ptid=PropertyType.ptid AND ListProperty.locid=locations.locid) 
  AND ListProperty.lpid IN (select lpid from ListPropertyMore WHERE ListProperty.locid IN (12,18) ) 
  AND ListPropertySortData.lpid=ListProperty.lpid 
  AND expdate>=CURDATE() AND status='T' 
GROUP BY PropertyType.ptype,PropertyType.category,locations.location
HAVING COUNT(DISTINCT ListProperty.lpid)=2

答案 3 :(得分:0)

您可以更好地使用IN操作数;

AND ListProperty.lpid IN (select lpid from ListPropertyMore WHERE ListProperty.locid IN (12,18) )

但是对于你的方法,你已经倒退了,我会在开头和结尾添加逗号,因为你会得到部分匹配,其中添加的逗号使它更加明显: AND ListProperty.lpid IN (select lpid from ListPropertyMore WHERE ',12,18,' LIKE CONCAT('%,',ListProperty.locid,',%' )

使用相同的CSV方案,Arion的答案比上面“手动”处理更容易。

相关问题