SubQuery使用IN运算符

时间:2014-12-02 08:29:46

标签: mysql sql select in-operator find-in-set

  

我有一个名为' user_permission'有一个名为location_ids的列,数据类型为varchar(255)。我在这里存储了像 10,27,36 这样的值。现在我想使用这个' location_ids'在 IN比较运算符中。我尝试过以下查询,但是我没有得到预期的结果。

SELECT (SELECT GROUP_CONCAT( `name` SEPARATOR ',' ) as name FROM location WHERE `remove` = 0 AND id IN(up.location_ids)) AS name FROM user_permission AS up
  

但是如果我提供IN(10,27,36)而不是IN(up.location_ids)那么它就可以了。

2 个答案:

答案 0 :(得分:1)

使用FIND_IN_SET()功能

试试这个:

SELECT up.id, GROUP_CONCAT(l.name) AS `name`
FROM user_permission AS up 
LEFT JOIN location l ON FIND_IN_SET(l.id, up.location_ids) AND l.remove = 0
GROUP BY up.id;

SELECT (SELECT GROUP_CONCAT(`name` SEPARATOR ',') AS NAME 
        FROM location 
        WHERE `remove` = 0 AND FIND_IN_SET(id,up.location_ids)
      ) AS NAME 
FROM user_permission AS up;

答案 1 :(得分:0)

看看是否有效

SELECT (SELECT GROUP_CONCAT( `name` SEPARATOR ',' ) as name FROM location WHERE `remove` = 0 AND id IN(select location_ids from user_permission)) AS name FROM user_permission