Rails MySQL query using where statement

I have this users:

NAME _____ ROLE _________ STATUS

user1 -------- role1 ---------------- true

user2 -------- role2 ---------------- true

user3 -------- role2 ---------------- false

user4 -------- role3 ---------------- false

user5 -------- role4 ---------------- true

I have this query:

User.where("role = ? OR role = ? OR role = ? AND status = ?", "role1", "role2", "role3", true)

and i expect that the data will be retrieve is:

user1

user2

but the system retrieve the user3 even if his status is false.

I also try to change AND to OR but it retrieves all.

what's wrong about my query?


What's wrong with the query is the lack of parentheses around the 'OR groups'

User.where("(role = ? OR role = ? OR role = ?) AND status = ?", "role1", "role2", "role3", true)

However, as already stated in another answer, it can be done in an easier way like this.

User.where(status: true).where(role: %w{role1 role2 role3})

尝试这个 :

User.where(status: true).where(role: ["role1", "role2", "role3"])

链接地址: http://www.djcxy.com/p/95052.html

上一篇: 根据输入或不输入的信息对MYSQL中的多个文本字段进行排序

下一篇: 使用where语句引导MySQL查询