简体   繁体   English

从一个SQL查询计算不同的数据

[英]Count different data from one SQL query

I want to get the same results in SQL 2 as in SQL 1 but somehow that SQL query only count the total amount of data for every date, based on the WHERE . 我想在SQL 2中获得与在SQL 1中相同的结果,但是以某种方式,SQL查询仅基于WHERE每个日期的数据总量。

SQL 1 (displays the right amount of data for each day) SQL 1 (每天显示正确的数据量)

SELECT DATE(datetime_logged) AS date,
COUNT(data_status) AS status_a

FROM activity
WHERE id_user = '1'
AND DATE(datetime_logged) != CURDATE()
AND data_status = 'online'
GROUP BY DATE(datetime_logged)
ORDER BY DATE(datetime_logged) DESC
LIMIT 40

结果1

SQL 2 (displays the wrong amount of data for each day) SQL 2 (每天显示错误的数据量)

SELECT DATE(datetime_logged) AS date,
(SELECT COUNT(data_status) 
         FROM activity 
         WHERE id_user = '1' 
         AND DATE(datetime_logged) != CURDATE() 
         AND data_status = 'online') AS status_a

FROM activity
GROUP BY DATE(datetime_logged)
ORDER BY DATE(datetime_logged) DESC
LIMIT 40

结果2

The table 桌子

CREATE TABLE IF NOT EXISTS `activity` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user` int(11) NOT NULL,
  `id_channel` varchar(50) NOT NULL,
  `id_game` int(11) NOT NULL,
  `data_muted_server` tinyint(4) NOT NULL,
  `data_muted_self` tinyint(4) NOT NULL,
  `data_deafen_server` tinyint(4) NOT NULL,
  `data_deafen_self` tinyint(4) NOT NULL,
  `data_suppressed` tinyint(4) NOT NULL,
  `data_status` varchar(10) NOT NULL,
  `data_game` text,
  `datetime_logged` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `index_datelog` (`datetime_logged`)
)

How can I accomplish this? 我该怎么做?

If I understand you correctly, I think you just need to tie the correlated subquery to the main query with: 如果我对您的理解正确,我认为您只需要使用以下方法将相关子查询与主查询绑定:

AND a.datetime_logged=sub.datetime_logged

Example: 例:

SELECT DATE(a.datetime_logged) AS date,
(SELECT COUNT(sub.data_status) 
         FROM activity sub
         WHERE sub.id_user = '1' 
         AND DATE(sub.datetime_logged) != CURDATE() 
         AND sub.data_status = 'online'
         AND a.datetime_logged=sub.datetime_logged) AS status_a

FROM activity a
GROUP BY DATE(a.datetime_logged)
ORDER BY DATE(a.datetime_logged) DESC
LIMIT 40

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM