使用单个id列查询逗号分隔列?

时间:2016-06-10 09:19:01

标签: php mysql

我正在尝试获取一个结果,其中单个列ID就像逗号分隔的列,我的两个表如下:

房间位置表

enter image description here

活动表

enter image description here

用户表

enter image description here

我的查询是

$sql=" SELECT users.*, events.*, room_location.* 
       FROM   events 
           INNER JOIN room_location ON events.event_room = room_location.location 
           INNER JOIN users ON room_location.user_loc_id = users.userlocationaccess 
       WHERE  room_location.user_loc_id LIKE '%1,2%'";

$result = $conn->query($sql);

如果我在users-> userGroupLocID中使用单个id,则上述查询有效。

如何修改我的查询以便查找id是否与我的逗号分隔列相同?

1 个答案:

答案 0 :(得分:2)

您可以使用FIND_IN_SET(str,strlist)功能搜索CSV字段。

示例

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
    -> 2

文档说

  

如果字符串str在,则返回1到N范围内的值   字符串列表strlist由N个子串组成。字符串列表是   由“,”字符分隔的子串组成的字符串。

您可以在userGroupLocID

中传递用户位置ID
select find_in_set( location_id_in_search, replace( userGroupLocID, ' ', '' ) )
  from table_name;