例如,我有2个表' meta'和' log'
在元表中:
| type | score |
|------|-------|
| a | 1 |
| b | 2 |
| c | 3 |
在日志表中:
| log_id | log_type | object_id |
|--------|----------|-----------|
| 1 | a | 13 |
| 2 | b | 13 |
| 3 | a | 14 |
| 4 | c | 14 |
| 5 | b | 15 |
| 6 | c | 15 |
所以我们知道:
object 13 got score: a+b = 3
object 14 got score: a+c = 4
object 15 got score: b+c = 5
我想按对象ID查询日志表组,并按对象得分的总和来查询,是否可以?
答案 0 :(得分:1)
select log.object_id, sum(meta.score)
from log
left join meta on meta.type = log.log_type
group by log.object_id
order by sum(meta.score) desc
答案 1 :(得分:1)
这将产生所需的输出
SELECT object_id, sum(score) from log
INNER JOIN meta on meta.type = log.log_type group by object_id ORDER BY sum(score);
但你有正确的桌子设计吗?您需要加入meta.type和log.log_type列,但这意味着如果log_type
是' a'对于所有object_id
来说,3的值是常见的,这真的是你想要的吗?
答案 2 :(得分:0)
试试这个
Select object_id,sum(score) as c FROM `log` as a INNER JOIN `meta` as b on a.log_type=b.type group by object_id order by c desc
答案 3 :(得分:0)
SELECT log.object_id, sum(score) total_score
FROM meta
INNER JOIN log on meta.type = log.log_type
GROUP BY log.object_id