MySQL计算特定的日期时间

时间:2017-03-26 07:47:02

标签: mysql

我想用单个数据库查询计算行数。

我的数据库有以下表格:

CREATE TABLE `messages` (
    `id` int(11) NOT NULL,
    `sender` int(11) DEFAULT NULL,
    `receiver` int(11) DEFAULT NULL,
    `time_send` datetime DEFAULT NULL,
    `time_read` datetime DEFAULT NULL,
    `subject` varchar(255) DEFAULT NULL,
    `message` longtext,
    PRIMARY KEY (`id`),
    KEY `sender` (`sender`),
    KEY `receiver` (`receiver`),
    CONSTRAINT `receiver` FOREIGN KEY (`receiver`) REFERENCES `ctn_users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `sender` FOREIGN KEY (`sender`) REFERENCES `ctn_users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

抽样数据:

INSERT INTO `messages` VALUES (1, 0, 1, '2017-3-26 09:22:39', '0000-0-0 00:00:00', 'Welcome!', 'Hey!');
  

信息:ID为0的用户是系统用户;请勿从users-table

中询问自动增量错误

我的问题是计算特定值,例如我想要跟随查询结果

read    unread    send
0       1         0

这是我的第一次尝试:

SELECT
    COUNT(???) AS `read`,
    COUNT(???) AS `unread`,
    COUNT(???) AS `send`
FROM
    `messages`
WHERE
    `receiver`=1

2 个答案:

答案 0 :(得分:1)

您正在尝试count fields with condition (Conditional Count),因此我们可以使用此COUNT(DISTINCT CASE WHEN time_read > '0000-0-0 00:00:00' THEN time_read ELSE 0 END) as ReedMessages 功能来计算阅读消息:

sender

此查询未返回最终结果,因为reciver中没有count(condition)Sum条件。 (见Stefano Zanini的回答)

我们也可以使用SELECT SUM(case when `receiver` = 1 and time_read > '0000-0-0 00:00:00' then 1 else 0 end) as read SUM(case when `receiver` = 1 and time_read = '0000-0-0 00:00:00' then 1 else 0 end) as unread SUM(case when `sender` = 1 then 1 end) as send FROM `tblName` 功能:

{{1}}

答案 1 :(得分:1)

.中需要case,并将条件从count移至where

case