Java / Ebean 与或查询
Java / Ebean And Or Query
我正在尝试执行 sql 查询:
select * from conversations where (user_1 = user_1_id and user_2 = user_2_id ) or (user_1 = user_2_id and user_2 = user_1_id )
我是这样用 Ebean 写的:
Conversation conversation = Ebean.find(Conversation.class)
.where()
.and(Expr.eq("user_1", user_1_id), Expr.eq("user_2", user_2_id))
.or(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id))
.findUnique();
但是这给出了以下查询:
select * from conversation where (user_1 = user_1_id and user_2 = user_2_id ) and (user_1 = user_2_id or user_2 = user_1_id )
我一直在查看文档,但我不清楚如何优化查询以满足我的需要。
有人能帮忙吗?
看看 JavaDoc(它有一个 或 表达式作为示例):
// Example: Using an Expr.or() method
Query<Order> query = Ebean.createQuery(Order.class);
query.where(
Expr.or(Expr.eq("status", Order.NEW),
Expr.gt("orderDate", lastWeek));
List<Order> list = query.findList();
这可能更容易理解为什么使用此代码:
.or(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id))
结果:
(user_1 = user_2_id or user_2 = user_1_id )
可以这么说,您使用 or 表达式 inside 您的第二个条件,而不是 between 两个条件.
你需要把or
方法放在第一位:
Conversation conversation = Ebean.find(Conversation.class)
.where().or(
Expr.and(Expr.eq("user_1", user_1_id), Expr.eq("user_2", user_2_id)),
Expr.and(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id)))
.findUnique();
这应该将 or 放在括号之间,并在其中放置 and 条件。
我正在尝试执行 sql 查询:
select * from conversations where (user_1 = user_1_id and user_2 = user_2_id ) or (user_1 = user_2_id and user_2 = user_1_id )
我是这样用 Ebean 写的:
Conversation conversation = Ebean.find(Conversation.class)
.where()
.and(Expr.eq("user_1", user_1_id), Expr.eq("user_2", user_2_id))
.or(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id))
.findUnique();
但是这给出了以下查询:
select * from conversation where (user_1 = user_1_id and user_2 = user_2_id ) and (user_1 = user_2_id or user_2 = user_1_id )
我一直在查看文档,但我不清楚如何优化查询以满足我的需要。
有人能帮忙吗?
看看 JavaDoc(它有一个 或 表达式作为示例):
// Example: Using an Expr.or() method
Query<Order> query = Ebean.createQuery(Order.class);
query.where(
Expr.or(Expr.eq("status", Order.NEW),
Expr.gt("orderDate", lastWeek));
List<Order> list = query.findList();
这可能更容易理解为什么使用此代码:
.or(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id))
结果:
(user_1 = user_2_id or user_2 = user_1_id )
可以这么说,您使用 or 表达式 inside 您的第二个条件,而不是 between 两个条件.
你需要把or
方法放在第一位:
Conversation conversation = Ebean.find(Conversation.class)
.where().or(
Expr.and(Expr.eq("user_1", user_1_id), Expr.eq("user_2", user_2_id)),
Expr.and(Expr.eq("user_1", user_2_id), Expr.eq("user_2", user_1_id)))
.findUnique();
这应该将 or 放在括号之间,并在其中放置 and 条件。