mysql-where_in和find_in_set之间的区别
作者:互联网
我正在研究一个联接查询,其中我必须从包含逗号分隔值的列中获取数据.例如allowed_activity包含1,2,3,4,5,6
这是被允许的activity_id.
因此,在查询中,我正在检查是否允许当前活动,为此,我使用了where_in并在where条件中尝试了find_in_set.
这是查询的一部分:
$this->db->where_in('a.allowed_activity',$activity_id);
//And With FIND_IN_SET
$this->db->where("FIND_IN_SET($activity_id, a.allowed_activity) !=",0);
问题或困惑
当我使用where_in时,不会得到结果.但是,如果我使用FIND_IN_SET,它将返回所需的结果.我以为where_in可以完成任务,但没有.
Just Want to know why
find_in_set
working differently than
where_in
Because of both the function work same as finding the data is in comma separated list.
这是完整的查询:
SELECT mycolumns
FROM `table1` as `ea`
LEFT OUTER JOIN `table2` as `a` ON `ea`.`package_id` = `a`.`id`
LEFT OUTER JOIN `table3` as `e` ON `ea`.`employer_id` = `e`.`id`
WHERE `ea`.`card_id` > 0
AND FIND_IN_SET(6, a.allowed_activity) !=0
AND `ea`.`id` = '6'
ORDER BY `ea`.`creation_date` DESC
我正在使用Codeigniter Active记录.
解决方法:
WHERE IN要求在查询中按字面值指定一组值,而不是包含逗号分隔字符串的单个值.如果您写:
WHERE 6 IN (a.allowed_activity)
它将a.allowed_activity视为单个值,并将其与6进行比较,而不是将其作为多个要搜索的值的集合.
FIND_IN_SET在逗号分隔的字符串中搜索该值.
另一种查看方式是IN是一堆=测试和OR结合的快捷方式:
WHERE x IN (a, b, c, d)
是短的
WHERE x = a OR x = b OR x = c OR x = d
当您以这种方式重写它时,您可以清楚地看到为什么它不适用于包含逗号分隔的字符串的列.它只是翻译
WHERE 6 IN (a.allowed_activity)
至:
WHERE 6 = a.allowed_activity
标签:mysql,codeigniter,where-in,find-in-set 来源: https://codeday.me/bug/20191013/1905665.html