我的数据库中有以下表格:
names:
id | name |
---|----------|
1 | Mark |
2 | George |
3 | Liza |
4 | Tai |
evaluation
name_id | score |
--------|----------|
1 | 30 |
1 | 100 |
2 | 20 |
3 | 40 |
3 | 50 |
4 | 40 |
4 | 50 |
bonuses
name_id | bonus |
--------|----------|
1 | 5 |
1 | 1 |
1 | 60 |
2 | 2 |
2 | 8 |
4 | 12 |
4 | 50 |
虽然您看到每个名字都有一个或两个评估,以及许多(或没有)奖金。
我需要MYSQL查询以获得最佳评估。分数并将其与所有bonuses.bonus相加,然后根据总和订购名称。
我尝试了以下但似乎我遗漏了一些东西:
SELECT
bonuses.name_id,
SUM(bonuses.bonus + evaluation.score) Total
From bonuses, evaluation
WHERE bonuses.name_id = evaluation.name_id
group by names.id
order by Total
请帮我在查询中引用问题 感谢
答案 0 :(得分:2)
试试这个:
SELECT bonuses.name_id, SUM(bonuses.bonus + evaluation.score) Total
FROM names, bonuses, evaluation
WHERE bonuses.name_id = evaluation.name_id
GROUP BY names.id
ORDER BY Total
您在FROM语句中缺少表names
。
答案 1 :(得分:2)
请查看此演示:
查询:
select n.id, n.name,
(coalesce(max(e.score),0) +
coalesce(sum(distinct b.bonus),0)) as maxscorebonus
from name n
left join
evaluation e
on n.id = e.name_id
left join
bonuses b
on b.name_id = e.name_id
group by n.id
;
结果:
| ID | NAME | MAXSCOREBONUS |
-------------------------------
| 1 | Mark | 166 |
| 2 | George | 30 |
| 3 | Liza | 50 |
| 4 | Tai | 112 |
答案 2 :(得分:1)
SELECT
n.name as Name,
IFNULL(SUM(e.score),0) + IFNULL(SUM(b.bonus),0) as Total
FROM names as n
LEFT JOIN evaluation as e ON n.id = e.name_id
LEFT JOIN bonuses as b ON b.name_id = e.name_id
GROUP BY n.id
答案 3 :(得分:0)
SELECT n.id,
(
SELECT COALESCE(MAX(e.score), 0)
FROM evaluations e
WHERE e.name_id = n.id
) +
(
SELECT COALESCE(SUM(b.bonus), 0)
FROM bonuses b
WHERE b.name_id = n.id
) AS total
FROM names n
ORDER BY
total
答案 4 :(得分:0)
这里我加入names
和bonuses
,为每个用户加总所有奖金,我加入一个子查询,我计算每个用户的最高分数。然后我将最大值与奖金总和相加:
select
names.id,
names.name,
coalesce(max_score, 0) + coalesce(sum(bonus), 0) as total
from
names left join bonuses
on names.id=bonuses.name_id
left join (
select
name_id,
max(score) as max_score
from evaluation
group by name_id
) mx
on names.id=mx.name_id
group by names.id,names.name
order by total desc
如果用户没有奖金或没有分数,则需要合并。