按问题加入两个表和组

时间:2014-01-20 23:44:29

标签: mysql sql

我有两张桌子:

问题

id | name

响应

id | problem_id | user_id | value

我有以下声明。

SELECT 
`problems`.name, 
problem_id, 
sum(value) as knowledge, 
COUNT(*) as attempts FROM `responses`
LEFT JOIN `problems` ON `problems`.id = `responses`.problem_id
WHERE problem_id IS NOT NULL AND user_id = 4
GROUP BY problem_id

它产生一个如下列表:

| name      | problem_id | knowledge | attempts |
| NULL      | 1          | 6         | 6        |
| NULL      | 2          | 5         | 6        |
| NULL      | 3          | 4         | 6        |
| NULL      | 4          | 3         | 5        |

我错过了一些内容,如果有人可以帮助格式化,我将不胜感激:

| name      | problem_id | knowledge | attempts |
| Problem A | 1          | 6         | 6        |
| Problem B | 2          | 5         | 6        |
| Problem C | 3          | 4         | 6        |
| Problem D | 4          | 3         | 5        |

2 个答案:

答案 0 :(得分:2)

试试这个。

select p.`name`, p.`id`, r.`user_id`, sum(r.`value`) as knowledge
from
`responses` r
join `problems` p on r.`problem_id` = p.`id`
where
r.`user_id` = 4
group by p.`name`, p.`id`

答案 1 :(得分:1)

你的SELECT既不能是聚合函数(如SUM或AVG),也不能是GROUP BY的可变部分。

在您的情况下,名称不是。

有些DBMS可能会让你这样做(MySQL),但结果是不可预测的。

解决方案:

SELECT 
`problems`.name, 
problem_id, 
sum(value) as knowledge, 
COUNT(*) as attempts FROM `responses`
LEFT JOIN `problems` ON `problems`.id = `responses`.problem_id
WHERE problem_id IS NOT NULL AND user_id = 4
GROUP BY problem_id, problems.name