我需要MySQL天才的建议。
表1' objects
':
ID (int,key,autoincrement) | hash(text) | name(text)
表2' logs
':
ID (int,key,autoincrement) | hash(text) | type(int) | time(text) | sum(int)
表1' objects
'链接表2' logs
'按专栏' hash
'。该列包含MD5值。
我需要以这种方式为每个对象获取type=1 or 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
答案 0 :(得分:2)
您可以使用CASE
根据类型1/2获取总和,并使用
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