MariaDB查询不能用“Where not in”在laravel中工作

isr3a4wc  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(157)

我有一个MariaDB查询,在数据库查询中运行良好。

SELECT student_id, last_name, first_name , Count(id) as courses FROM registrations
WHERE student_id NOT IN (SELECT student_id FROM exclude_from_tracking_list)
GROUP BY student_id
HAVING COUNT(*) > 3
ORDER BY last_name

但是不能在Laravel 8中运行。

DB::statement('with query')

DB::table('registrations') 
        ->selectRaw('student_id, last_name, first_name , Count(id) as courses')
        ->where(DB::raw('student_id NOT IN (SELECT student_id FROM exclude_from_tracking_list'))    
        ->groupBy('student_id')
        ->havingRaw('COUNT(*) > 3')
        ->orderBy('last_name')
        ->get();

我错过了什么。我已经搜索并尝试了许多其他选项。
但我一直收到这个错误
数据库状态[42000]:语法错误或访问冲突:1064 0x 0064您的SQL语法有错误;检查与您的MariaDB服务器版本对应的手册,以获得正确的语法,在第1行使用near 'is null group by student_id having COUNT()〉3 order by last_name asc'(SQL:select student_id,last_name,first_name,Count(id)as courses from registrations where student_id NOT IN(SELECT student_id FROM exclude_from_tracking_list is null group by student_id having COUNT()〉3 order by last_name asc)
任何帮助都将不胜感激。

q9yhzks0

q9yhzks01#

您的错误消息包括“is null”,但在您显示的代码中没有类似的内容。但是,通常您应该始终将原始语句的使用保持在最低限度。应该首选这样的内容,并且可能会解决您看到的错误。

$excluded = DB::table('exclude_from_tracking_list')->select('student_id');

$result = DB::table('registrations')
    ->select('student_id', 'last_name', 'first_name')
    ->selectRaw('count(id) as courses')
    ->whereNotIn('student_id', $excluded)
    ->groupBy('student_id')
    ->having('courses', '>', 3)
    ->orderBy('last_name')
    ->get();

有关可用的查询生成器方法,请参阅Laravel documentation。有关故障排除,请将get()替换为toSql()并检查输出。

相关问题