我正在运行查询但是当我运行它时,它会返回一个
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' count(distinct exams.user_id) as count_user_mhs from `users` where `users.type`' at line 1 (SQL: select `universities`.`name`, count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0, count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1, count(exams.subject_id) as count_subject, sum(exams.score) as count_score, TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time from `exams` inner join `universities` on `universities`.`id` = `exams`.`university_id` inner join `users` on `users`.`id` = `exams`.`user_id` where exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`) group by `user_id` order by `count_score` desc, `count_time` asc)
$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
->join('users', 'users.id', '=', 'exams.user_id')
->select('universities.name',DB::raw('count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0'),DB::raw('count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1'),DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time'));
有人可以帮忙吗?我猜,它与DB::raw
表达式有关。但我不确切地知道出了什么问题。
答案 0 :(得分:0)
您生成的查询如下所示:
select
`universities`.`name`,
count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0,
count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1,
count(exams.subject_id) as count_subject,
sum(exams.score) as count_score,
TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time
from
`exams`
inner join
`universities` on `universities`.`id` = `exams`.`university_id`
inner join
`users` on `users`.`id` = `exams`.`user_id`
where
exists (select * from `universities` where `exams`.`university_id` = `universities`.`id`)
group by
`user_id`
order by
`count_score` desc,
`count_time` asc
问题出在第3和第4行,由DB::raw
代码生成。
要解决此问题,您需要更新您的Eloquent查询:
<?php
$exams = Exam::join('universities', 'universities.id', '=', 'exams.university_id')
->join('users', 'users.id', '=', 'exams.user_id')
->select(
'universities.name',
DB::raw('(select count(distinct exams.user_id) as count_user_dsn from `users` where `users.type` = 0)'),
DB::raw('(select count(distinct exams.user_id) as count_user_mhs from `users` where `users.type` = 1)'),
DB::raw('count(exams.subject_id) as count_subject'),DB::raw('sum(exams.score) as count_score'),
DB::raw('TIME_FORMAT(SUM(TIMEDIFF(exams.exam_end_date, exams.exam_start_date)), "%H:%i:%s") as count_time')
);
那就是说...在主SELECT COUNT
语句中执行SELECT
子查询不是一个好主意,因为它们将针对主查询选择的每一行执行。