【发布时间】:2020-05-31 08:32:13
【问题描述】:
基本上我有两张桌子。 answers 和 choices 。在我的choices 表中,我有一个列choices.value,其值为0-4。我目前的查询是这样的
$answers = \DB::table('answers')
->join('choices','answers.choice_id','=','choices.choice_id')
->select('answers.user_id','choices.choice_id','choices.choice','choices.value')
->where('answers.user_id',\Auth::user()->id)
//->groupBy('answers.user_id')
->get();
我现在的反应是这样的
"user_id": 2,
"choice_id": 2,
"choice": "I feel discourated about the future",
"value": 1
},
{
"user_id": 2,
"choice_id": 2,
"choice": "I don't enjoy things the way I used to",
"value": 1
},
{
"user_id": 2,
"choice_id": 2,
"choice": "I feel guilty a good part of time",
"value": 1
我如何添加值以便我的结果会像这样
"user_id":2,
"total_score":3
我尝试做DB::raw(SUM(choices.values)as score),但我得到了很多。我猜它是从选择表中添加所有选择值,而不是在答案中。
我的答案数据库,我只选择用户的答案 = 2。我限制为 5
+---------+-------------+-----------+
| user_id | question_id | choice_id |
+---------+-------------+-----------+
| 2 | 1 | 2 |
| 2 | 2 | 2 |
| 2 | 3 | 2 |
| 2 | 4 | 2 |
| 2 | 5 | 2 |
+---------+-------------+-----------+
我的选择表,我只选择问题1和2以及他们的选择。
+-----------+-------------+--------------------------------------------------------------+-------+
| choice_id | question_id | choice | value |
+-----------+-------------+--------------------------------------------------------------+-------+
| 1 | 1 | I do not feel sad | 0 |
| 2 | 1 | I feel sad | 1 |
| 3 | 1 | I am sad all the time and I can't snap out of it | 2 |
| 4 | 1 | I am so sad and unhappy that I can't stand it | 3 |
| 1 | 2 | I am not particularly discouraged about the future | 0 |
| 2 | 2 | I feel discourated about the future | 1 |
| 3 | 2 | I feel I have nothing to look forward to | 2 |
| 4 | 2 | I feel the future is hopeless and that things cannot improve | 3 |
+-----------+-------------+--------------------------------------------------------------+-------+
我还想创建一个名为scores 的新表,列将是我想要的结果。我想在每个answers.user_id 的答案中添加choices.values,这样当我查看分数表时,它将显示每个用户的总分,或者当用户回答完所有21 问题时,因为我只有21 个问题它会自动添加到scores 表中的项目。我可以这样做吗?是否可以在基于choice_id 的answers 表中添加value?这就是我的想法,但我认为它是多余的,因为choice_id 已经存在。提前致谢。
PS:尝试编写这些查询,但总是得到 441,这是 choices 表中所有选项的总数 value
SELECT answers.user_id,choices.choice_id,choices.value,COALESCE(sum(choices.value),0) as score FROM
`answers` JOIN `choices` ON choices.choice_id = answers.choice_id where
answers.user_id = 2
SELECT answers.user_id,choices.choice_id,choices.value,SUM(choices.value),0 as score FROM `answers`
join choices on choices.choice_id = answers.choice_id
where answers.user_id = 2
SELECT answers.user_id,choices.choice_id, sum(choices.value) from answers
JOIN `choices` ON choices.choice_id = answers.choice_id
group by answers.user_id
【问题讨论】:
标签: php mysql sql laravel laravel-query-builder