Laravel中如何获取表1中不存在于表2的数据?

表1
| ID | val1 |
|---|---|
| 1 | a |
| 2 | b |
| 3 | c |
表2
| ID | val1 |
|---|---|
| 1 | a |
| 2 | b |
需求:获取表1中不存在于表2的数据(即ID为3的记录)
你用的rightJoin逻辑不符合需求,它会返回右表(user_infos)的所有数据以及左表(users)匹配的部分,无法筛选出左表独有的数据。以下是两种正确的实现方式:
方法一:使用whereNotExists
$users_without_info = DB::table('users') ->whereNotExists(function ($query) { $query->select(DB::raw(1)) ->from('user_infos') ->whereRaw('users.email = user_infos.email'); }) ->latest() ->get();
方法二:使用leftJoin + whereNull
$users_without_info = DB::table('users') ->leftJoin('user_infos', 'users.email', '=', 'user_infos.email') ->whereNull('user_infos.email') ->select('users.*') ->latest() ->get();
这两种方式都能精准筛选出users表中没有对应user_infos记录的数据。
内容的提问来源于stack exchange,提问作者Thineshraj S
相关产品推荐
相关产品推荐

