Activerecord和+或有多个标准的条件

发布于 2025-01-18 06:44:56 字数 879 浏览 1 评论 0原文

我正在使用activerecord来构建查询,并且与生成的SQL有一个括号问题。

这是创建我的问题的查询

joined_users = User.joins(:consumer)

users = joined_users.where(id: (1..3), name: 'foo').or(joined_users.where(consumer: {id: (1...4))

,它创建了以下SQL,

SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE ("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo' OR "consumer"."id" >= 1 AND "consumer"."id" < 4)

但实际上,您应该

SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE (("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo') OR ("consumer"."id" >= 1 AND "consumer"."id" < 4))

明白我的意思吗?

缺少括号将第一个分隔为,其中用将其分开。

在有和没有这些括号的情况下,Bool逻辑完全不一样。

我想念什么?

I'm using ActiveRecord to build a query and I got a parenthesis issue with generated SQL.

Here is a query creating my problem

joined_users = User.joins(:consumer)

users = joined_users.where(id: (1..3), name: 'foo').or(joined_users.where(consumer: {id: (1...4))

It creates the following SQL

SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE ("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo' OR "consumer"."id" >= 1 AND "consumer"."id" < 4)

But actually, it should be

SELECT "users".* FROM "users" INNER JOIN "consumers" "consumer" ON "consumer"."user_id" = "users"."id" WHERE (("users"."id" BETWEEN 1 AND 3 AND "users"."name" = 'foo') OR ("consumer"."id" >= 1 AND "consumer"."id" < 4))

Do you get my point?

There are missing parenthesis separating the first where to the second with the or.

Bool logic is not the same at all with and without these parenthesis.

What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

债姬 2025-01-25 06:44:56

在您的特定情况下,查询结果应该没有差异,因为逻辑 AND 运算符比逻辑 OR 具有更高的优先级,因此:

A &&乙|| C&& D 等于 (A && B) || (C && D)

ActiveRecord 会在需要时添加括号,例如:

User.where(id: 1..3).or(User.where(id: 4...5)).where(email: 'some')

将导致:

SELECT "users".* FROM "users" WHERE ("users"."id" BETWEEN 1 AND 3 OR "users"."id" >= 4 AND "users"."id" < 5) AND "users"."email" = 'some'

I your particular case there should be no difference in query result, because logical AND operator has higher priority than logical OR, so:

A && B || C && D equals (A && B) || (C && D)

ActiveRecord will add parenthesis when it is needed, for example:

User.where(id: 1..3).or(User.where(id: 4...5)).where(email: 'some')

Will result in:

SELECT "users".* FROM "users" WHERE ("users"."id" BETWEEN 1 AND 3 OR "users"."id" >= 4 AND "users"."id" < 5) AND "users"."email" = 'some'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文