选择不在另一个表 laravel 5.5 中的所有列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46384610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
select all columns which are not in another table laravel 5.5
提问by Rashed Hasan
I have two tables - the first one is called 'users' and the second one is called 'buy_courses'.
我有两个表 - 第一个称为“用户”,第二个称为“buy_courses”。
I am trying to select all users those user_name is not in buy_courses. I tried something like -
我正在尝试选择那些 user_name 不在 buy_courses 中的所有用户。我试过类似的东西 -
$users = DB::table('users')
->rightjoin('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
It returns all users, whose user_name is in 'buy_courses', when I am using '<>', then I'm getting all users. What should be the right query?
当我使用“<>”时,它返回用户名在“buy_courses”中的所有用户,然后我得到所有用户。什么应该是正确的查询?
回答by Markownikow
DB::table("users")->select('*')->whereNotIn('user_name',function($query) {
$query->select('user_name')->from('buy_courses');
})->get();
just joinactually is inner join in Laravel so actually maybe also you can try:
只是加入实际上是 Laravel 的内部加入所以实际上也许你也可以尝试:
DB::table('users')
->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
回答by anayarojo
Try it using Eloquent:
使用 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();
回答by azbatuk
You can use SQL's 'NOT IN'.
您可以使用 SQL 的“NOT IN”。
Example:
例子:
mysqli_query($con, "SELECT * FROM users WHERE user_name NOT IN (SELECT user_name FROM buy_courses)");