SQL counting all rows instead of counting individual rows(SQL 计算所有行而不是计算单个行)
问题描述
我有一个从数据库请求数据的 SQL 语句.
I have a SQL statement which requests data from the database.
SELECT `ID`, `To`, `Poster`, `Content`, `Time`, ifnull(`Aura`,0) as `Aura` FROM (
SELECT * FROM (
SELECT DISTINCT * FROM messages m
INNER JOIN
(
SELECT Friend2 as Friend FROM friends WHERE Friend1 = '1'
UNION ALL
SELECT Friend1 as Friend FROM friends WHERE Friend2 = '1'
) friends ON m.Poster = friends.`Friend`
UNION ALL SELECT DISTINCT *, '1' FROM messages where `Poster`='1'
) var
LEFT JOIN
(
select `ID` as `AuraID`, `Status` as `AuraStatus`, count(*) as `Aura`
from messages_aura
) aura ON (var.Poster = aura.AuraID AND var.ID = aura.AuraStatus)
) final
GROUP BY `ID`, `Poster`
ORDER BY `Time` DESC LIMIT 10
这是我的 messages_aura 表格布局.它显示 ID、Status 和 UserID.
Here is my messages_aura table layout. It shows ID, Status and UserID.
这是上述语句的输出.
(上面截图中的ID指的是下面的Poster,上面截图中的Status指的是ID代码> 下面)
(The ID from the above screenshot refers to Poster below and the Status from the above screenshot refers to ID below)
该语句应为底行提供 1 的 Aura 计数,并为顶行提供 2 的 Aura 计数.怎么了?
The statement should give the bottom row a Aura count of 1 and the top row an Aura count of 2. What's wrong?
推荐答案
您缺少 GROUP BY,因此它会计算所有内容,而不是按某些列分组.
You're missing GROUP BY, so it's counting everything instead of grouping by some columns.
LEFT JOIN
(
select `ID` as `AuraID`, `Status` as `AuraStatus`, count(*) as `Aura`
from messages_aura
GROUP BY AuraID, AuraStatus
) aura ON (var.Poster = aura.AuraID AND var.ID = aura.AuraStatus)
这篇关于SQL 计算所有行而不是计算单个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL 计算所有行而不是计算单个行
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
