我需要 MySQL 天才的建议。
Table1“对象
”:
ID (int,key,autoincrement) | hash(text) | name(text)
表2“日志
”:
ID (int,key,autoincrement) | hash(text) | type(int) | time(text) | sum(int)
Table1“objects
”通过“hash
”列与 Table2“logs
”链接。该列包含 MD5 值。
我需要以这种方式为每个对象获取 type=1 或 type=2
的数据:
Name | sum all rows for this name and type=1 | sum all rows for this name and type=2
尝试过这样的查询
SELECT name, SUM(sum) as tsum
FROM objects RIGHT JOIN logs using(hash)
WHERE (type='1' OR type='2')
GROUP BY type
但是它以格式形成数据
Name | sum all rows for this name and type=1
Name | sum all rows for this name and type=2
最佳答案
您可以使用CASE
根据类型1/2获取总和,并在group by中使用名称列
SELECT name,
SUM(case when type='1' then sum else 0 end) as firstsum ,
SUM(case when type='2' then sum else 0 end) as secondsum
FROM objects
RIGHT JOIN logs using(hash)
WHERE (type='1' OR type='2')
GROUP BY name
关于mysql - 如何在 MySQL 中构建这样的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918628/