mysql - 不存在查询

标签 mysql sql laravel query-builder

我有一个查询问题。

在帖子表中,我有 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/

相关文章:

php - 当我运行此代码时出现错误 :

php - 如果 pdo 数据库连接不存在,错误处理?

c# - Linq 导致 Top (1) 出现语法错误

每次操作后的 MySQL SUM 和 MIN

mysql - 如何通过在每次更新时插入另一行来获取尚未在 SQL 中更新的月份?

php - 将自定义函数添加到 Laravel 查询生成器

mysql - Laravel join 用于获取一对多关系?

php - 在 mysql 表的列中查找所有不同的值

php - 如何将这些数据存储在mysql中

php - Laravel session 没有破坏