我想用Rails进行查询,如下所示:
filters = Filter.joins(:category_filters).where("category_id IN (?)", params[:categories]).group("filters.id")
正在制作的MySQL声明就是:
SELECT `filters`.* FROM `filters` INNER JOIN `category_filters` ON `category_filters`.`filter_id` = `filters`.`id` WHERE (category_id IN ('9,4')) GROUP BY filters.id
乍一看,这个查询还可以,但是当我查看结果时,它的错误。我来解释一下。
首先,这是对表格过滤器的查询:
select * from filters;
+----+----------+-------+----------+------------+------------+
| id | name | other | optional | created_at | updated_at |
+----+----------+-------+----------+------------+------------+
| 1 | material | 1 | 1 | NULL | NULL |
| 2 | abc | 1 | 0 | NULL | NULL |
| 3 | xyz | 0 | 0 | NULL | NULL |
| 4 | 123a | 0 | 0 | NULL | NULL |
+----+----------+-------+----------+------------+------------+
其次,这是对table_filters表的查询:
select * from category_filters;
+----+-----------+-------------+------------+------------+
| id | filter_id | category_id | created_at | updated_at |
+----+-----------+-------------+------------+------------+
| 1 | 1 | 1 | NULL | NULL |
| 2 | 2 | 1 | NULL | NULL |
| 3 | 1 | 9 | NULL | NULL |
| 4 | 2 | 9 | NULL | NULL |
| 5 | 1 | 4 | NULL | NULL |
| 6 | 3 | 4 | NULL | NULL |
+----+-----------+-------------+------------+------------+
现在,Rails生成的查询(第一个查询):
SELECT `filters`.* FROM `filters` INNER JOIN `category_filters` ON `category_filters`.`filter_id` = `filters`.`id` WHERE (category_id IN ('9,4')) GROUP BY filters.id;
+----+----------+-------+----------+------------+------------+
| id | name | other | optional | created_at | updated_at |
+----+----------+-------+----------+------------+------------+
| 1 | material | 1 | 1 | NULL | NULL |
| 2 | abc | 1 | 0 | NULL | NULL |
+----+----------+-------+----------+------------+------------+
为什么会这样?
但是现在,这是类似的查询,而不是使用IN我使用OR,像这样:
SELECT `filters`.* FROM `filters` INNER JOIN `category_filters` ON `category_filters`.`filter_id` = `filters`.`id` WHERE (category_filters.category_id=9 or category_filters.category_id=4) GROUP BY filters.id;
+----+----------+-------+----------+------------+------------+
| id | name | other | optional | created_at | updated_at |
+----+----------+-------+----------+------------+------------+
| 1 | material | 1 | 1 | NULL | NULL |
| 2 | abc | 1 | 0 | NULL | NULL |
| 3 | xyz | 0 | 0 | NULL | NULL |
+----+----------+-------+----------+------------+------------+
发生了什么事?
答案 0 :(得分:2)
在你的WHERE子句中,试试这个(假设category_id是一个数字):
category_id IN (9,4)
否则这个(假设category_id是一个字符串)
category_id IN ('9','4')
而不是(在原始查询中)
category_id IN ('9,4')
答案 1 :(得分:2)
如果你这样做
where(:category_id => params[:categories]
Rails将为您创建正确的SQL语法