连接中的优先级和括号。我如何在反对 ORM 中写下 SQL 查询?
Precedence and parentheses In Join. How can I write below SQL query in objection ORM?
我有以下 SQL 查询:
select p.id, p.slug, p.post_author, b.id, b.is_deleted from posts p
left join blocks b
on
((b.blocked_id = p.post_author and blocker_id = <user id>)
or
(b.blocked_id = <user_id> and b.blocker_id = p.post_author))
and b.is_deleted = false
where b.id is null
order by posted_at desc limit 20
并且需要相应的反对 orm 声明,我不确定如何引入这些括号优先级。以下是我目前拥有的修饰符:
getUnblockedUsersPosts: (builder) => {
builder.leftJoin('blocks as b', function(){
this.on('b.blocked_id', '=', 'posts.post_author')
.andOn('b.blocker_id', '=', parseInt(user.id))
.orOn('b.blocked_id', '=', parseInt(user.id))
.andOn('b.blocker_id', '=', 'posts.post_author')
.andOn('b.is_deleted', knex.raw('false'))
}).where('b.id', 'is', null)
},
所以上面的查询是通过下面的代码解决的,
参考:https://knexjs.org/#Builder-join
getUnblockedUsersPosts: (builder) => {
builder.leftJoin('blocks as b', function(){
this.on(function(){
this.on(function(){
this.on('b.blocked_id', '=', 'posts.post_author')
.andOn('b.blocker_id', '=', parseInt(user.id))
})
this.orOn(function(){
this.on('b.blocker_id', '=', 'posts.post_author')
.andOn('b.blocked_id', '=', parseInt(user.id))
})
})
this.andOn('b.is_deleted', knex.raw('false'))
}).where('b.id', 'is', null)
}
我有以下 SQL 查询:
select p.id, p.slug, p.post_author, b.id, b.is_deleted from posts p
left join blocks b
on
((b.blocked_id = p.post_author and blocker_id = <user id>)
or
(b.blocked_id = <user_id> and b.blocker_id = p.post_author))
and b.is_deleted = false
where b.id is null
order by posted_at desc limit 20
并且需要相应的反对 orm 声明,我不确定如何引入这些括号优先级。以下是我目前拥有的修饰符:
getUnblockedUsersPosts: (builder) => {
builder.leftJoin('blocks as b', function(){
this.on('b.blocked_id', '=', 'posts.post_author')
.andOn('b.blocker_id', '=', parseInt(user.id))
.orOn('b.blocked_id', '=', parseInt(user.id))
.andOn('b.blocker_id', '=', 'posts.post_author')
.andOn('b.is_deleted', knex.raw('false'))
}).where('b.id', 'is', null)
},
所以上面的查询是通过下面的代码解决的, 参考:https://knexjs.org/#Builder-join
getUnblockedUsersPosts: (builder) => {
builder.leftJoin('blocks as b', function(){
this.on(function(){
this.on(function(){
this.on('b.blocked_id', '=', 'posts.post_author')
.andOn('b.blocker_id', '=', parseInt(user.id))
})
this.orOn(function(){
this.on('b.blocker_id', '=', 'posts.post_author')
.andOn('b.blocked_id', '=', parseInt(user.id))
})
})
this.andOn('b.is_deleted', knex.raw('false'))
}).where('b.id', 'is', null)
}