我有一个查询问题。
在帖子表中,我有 posts.id, 然后,在评论表中,我有 posts_id(外键 -> posts.id),reviews.id。 我想查询那些在评论表(post_id)中不存在的posts_id。
我正在使用 laravel 查询构建器。 我正在尝试 ->
$r = DB::table('reviews')
->select(DB::raw('count(id) as rev_count, posts_id'))
->groupBy('posts_id')
->get();
foreach ($r as $rr)
{
$p = DB::table('posts')
->select('id')
->where('id', '!=', $rr->posts_id)
->get();
}
我已经成功提取了值(value)。但是太复杂了,可能有问题。 如果有直接查询提取它?
最佳答案
如何使用不存在
,
SQL查询:
select *
from posts
where not exists
(select reviews.posts_id
from reviews
where reviews.posts_id = posts.id)
等效的 laravel
查询:
DB::table('posts')
->select('id')
->whereNotExists(function ($query) {
$query->select("reviews.posts_id")
->from('reviews')
->whereRaw('reviews.posts_id = posts.id');
})
->get();
有这个SO link也可能对你有用
关于mysql - 不存在查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64087958/