我有一个完美运行的子查询:
select GROUP_CONCAT(zone SEPARATOR ', ') from typeofru where id in (5,7) /*This works good*/
我遇到的问题是 5 和 7 一起在 varchar 列 ('5,7') 上,无法使其工作
select GROUP_CONCAT(zone SEPARATOR ', ') from typeofru where id in ('5,7') /*This is not working */
如何将 ('5,7') 转换为值类型以使其正常工作
我需要使用的最终查询是这样的,但似乎不起作用:
select name, (select GROUP_CONCAT(zone SEPARATOR ', ') from typeofru where id in (typeofru_ids)) from deviceru where device_id=5
最佳答案
使用FIND_IN_SET()
WHERE FIND_IN_SET(ID, '5,7') > 0
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.
作为一个教训,不要存储用逗号分隔的值。
如果逗号前后有空格,需要先替换空格,
WHERE FIND_IN_SET(ID, REPLACE(' 5 , 7', ' ','')) > 0
关于mysql 选择在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626507/