gpt4 book ai didi

mysql - MySQL中查询的疑惑

转载 作者:搜寻专家 更新时间:2023-10-30 22:02:51 24 4
gpt4 key购买 nike

我想用 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 |
+----+----------+-------+----------+------------+------------+

其次,这是对表 category_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 |
+----+----------+-------+----------+------------+------------+

发生了什么事?

最佳答案

在您的 WHERE 子句中,试试这个(假设 category_id 是一个数字):

category_id IN (9,4)

否则这个(假设category_id是一个字符串)

category_id IN ('9','4')

而不是这个(在您的原始查询中)

category_id IN ('9,4')

关于mysql - MySQL中查询的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8272521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com