Laravel中的单个查询

时间:2017-12-15 12:31:26

标签: php mysql sql laravel laravel-5

如何在laravel / mysql / php单一查询中计算(得分/无问题)

+=============+     +=============+    +===============+
|    User     |     |    Taken    |    |    Answers    |
+=============+     +=============+    +===============+
|     id      |     |   taken_id  |    |   answer_id   |
+-------------+     +-------------+    +---------------+
|     name    |     | user_id(FK) |    |  taken_id(FK) |
+-------------+     +-------------+    +---------------+
                    |  taken_date |    |  question_id  |
                    +-------------+    +---------------+
                                       |     choice    |
                                       +---------------+
                                       |      score    |
                                       +---------------+

我尝试了以下操作:(我从2张桌子中获得了大量的user_id并回答)

SELECT a.user_id, answers.score FROM (
    SELECT MAX(taken.taken_id) AS taken_id, taken.user_id FROM taken 
    GROUP BY taken.user_id ) a, answers 
WHERE a.taken_id = answers.taken_id 
AND answers.score IS NOT null

但是如何在此查询中使用用户表详细信息

2 个答案:

答案 0 :(得分:1)

您可以向用户表添加联接以获取用户

的详细信息
select u.id,
       u.name,
       a.score 
from (
    select max(taken_id) as taken_id, 
    user_id 
    from taken 
    group by user_id
) t
join answers a on t.taken_id = a.taken_id 
join user u on u.id = t.user_id
where a.score is not null

要获得每个用户的分数总和,您可以使用

select u.id,
       u.name,
       sum(a.score) score
from (
    select max(taken_id) as taken_id, 
    user_id 
    from taken 
    group by user_id
) t
join answers a on t.taken_id = a.taken_id 
join user u on u.id = t.user_id
where a.score is not null
group by u.id,u.name

答案 1 :(得分:0)

你可以尝试 -

EXECUTE

确保已导入数据库类。