[英]Doesn't exist query
我有一個查詢問題。
在posts表中,我有posts.id,然后在reviews表中,我有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();
}
我已成功提取該值。 但是太復雜了,可能有問題。 如果有直接查詢來提取它?
如何使用not exists
,
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 鏈接也可能對你有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.