【问题标题】:Doesn't exist query不存在查询
【发布时间】:2021-01-13 04:43:14
【问题描述】:

我的查询有问题。

在帖子表中,我有 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();
        }

我已成功提取该值。但过于复杂,可能有问题。 如果有直接查询来提取它?

【问题讨论】:

    标签: mysql sql laravel query-builder


    【解决方案1】:

    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 link 也可能对你有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2011-09-26
      相关资源
      最近更新 更多