You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

输入图片描述

表1

IDval1
1a
2b
3c

表2

IDval1
1a
2b

需求:获取表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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:55:17