mysql - 如何在 MySQL 中构建这样的查询

标签 mysql

我需要 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/

相关文章:

php - 连接第三个 MySQL 表(重做)

PHP MySQL 身份验证错误

mysql - 对文本列 : full-text or separate table 进行过滤

php - 从两个 mysql 表中选择的 mysql 查询

mysql - NOT NULL 单元格的 SQL 语法

php - Laravel 检查是否可以连接到数据库

mysql - 跨公司计算机共享数据库

mysql - 使用 SQL 对位置进行排名

mysql - 在 MySQL 中查找字符串中出现的子字符串?

mysql - 如何让 Navicat mySQL (Non-Commercial) 表默认为 InnoDB 引擎?