select all columns which are not in another table laravel 5.5

后端 未结 4 1368
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 04:05

I have two tables - the first one is called \'users\' and the second one is called \'buy_courses\'.

I am trying to select all users those user_name

相关标签:
4条回答
  • 2021-01-12 04:24

    You can use SQL's 'NOT IN'.

    Example:

    mysqli_query($con, "SELECT * FROM users WHERE user_name NOT IN (SELECT user_name FROM buy_courses)");
    
    0 讨论(0)
  • 2021-01-12 04:25

    just replace = with != , use function join

    $users = DB::table('users')
      ->join(
        'buy_courses', 
        function ($join)
        {$join->on('users.user_name', '!=', 'buy_courses.user_name');}
      )
      ->get();
    
    0 讨论(0)
  • 2021-01-12 04:45

    Try it using Eloquent:

    $courseUserNames = BuyCourses::pluck('user_name')->all();
    $users = User::whereNotIn('user_name', $courseUserNames)->select(...)->get();
    

    Or if you prefer using DB query:

    $courseUserNames = DB::table('buy_courses')->pluck('user_name')->all();
    $users = DB::table('users')->whereNotIn('user_name', $courseUserNames)->select(...)->get();
    
    0 讨论(0)
  • 2021-01-12 04:50
    DB::table("users")->select('*')->whereNotIn('user_name',function($query) {
    
       $query->select('user_name')->from('buy_courses');
    
    })->get();
    

    just join actually is inner join in Laravel so actually maybe also you can try:

    DB::table('users')
                ->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
                ->get();
    
    0 讨论(0)
提交回复
热议问题