我的sql查询中出现了一些意外的结果。 如果我要连接的表上有记录,当我应该得到每行都为null的集合时,我会得到一个空结果集,而我不知道为什么会这样?
昨天的数据仍在表中时,我得到一个empty result set
。如果我清空表并运行相同的查询,则会得到预期的结果集:
cnt | partner | today
0 | 3000 | NULL
0 | 3001 | NULL
0 | 3002 | NULL
0 | 3003 | NULL
0 | 3004 | NULL
0 | 3005 | NULL
0 | 3006 | NULL
0 | 3007 | NULL
我在做什么错了?
CREATE TABLE `partner` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'unik räknare' ,
`url` TEXT NOT NULL COMMENT 'webadress' ,
`imgurl` TEXT NOT NULL COMMENT 'bildurl' ,
`displayname` VARCHAR(256) NOT NULL COMMENT 'firmanamn' ,
`annons` TEXT NULL COMMENT 'annons ord' ,
PRIMARY KEY (`id`)
) ENGINE = MyISAM CHARSET=utf8 COLLATE utf8_swedish_ci AUTO_INCREMENT=3000 COMMENT = 'Tabell innehållande samarbetspartners (saps)';
CREATE TABLE `sap_daily_stats` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'unik räknare' ,
`partner` INT UNSIGNED NOT NULL COMMENT 'partner.id' ,
`servertime` INT UNSIGNED NOT NULL COMMENT 'datum' ,
`browser` VARCHAR(256) NOT NULL COMMENT 'HTTP_USER_AGENT' ,
`remoteaddr` VARCHAR(40) NOT NULL COMMENT 'REMOTE_ADDR' ,
`httpacclang` VARCHAR(72) NULL COMMENT 'HTTP_ACCEPT_LANGUAGE' ,
PRIMARY KEY (`id`)
) ENGINE = MyISAM CHARSET=utf8 COLLATE utf8_swedish_ci AUTO_INCREMENT=10000 COMMENT = 'Tabell innehållande dagens annonsstatistik';
SELECT
COUNT(`q`.`partner`) - (
CASE WHEN DATE_FORMAT(FROM_UNIXTIME(`d`.`servertime`),'%Y-%m-%d') IS NULL THEN 1
ELSE 0
END) AS `cnt`,
`q`.`partner`,
DATE_FORMAT(FROM_UNIXTIME(`d`.`servertime`),'%Y-%m-%d') AS `today`
FROM `sap_quotas` `q`
LEFT JOIN `sap_daily_stats` `d`
ON `q`.`partner` = `d`.`partner`
GROUP BY `q`.`partner`,`today`
HAVING `today` = CURDATE() OR `today` IS NULL
ORDER BY `today` IS NULL DESC,
`cnt` ASC,
`q`.`partner` ASC
不知道它是否与版本有关,但这是我当前的设置:
数据库服务器
Server: MySQL (127.0.0.1 via TCP/IP)
Server type: MySQL
Server version: 5.7.21 - MySQL Community Server (GPL)
Protocol version: 10
Server charset: UTF-8 Unicode (utf8)
Web服务器
Apache/2.4.33 (Win32) PHP/7.2.4
Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.2.4
答案 0 :(得分:1)
如果您有昨天的数据(按照OP)-那么LEFT JOIN将不会创建today
列为空的行。
获取空值的一种方法是在JOIN条件(如下所示)中而不是在HAVING条件中进行过滤。
LEFT JOIN `sap_daily_stats` `d`
ON `q`.`partner` = `d`.`partner`
and DATE_FORMAT(FROM_UNIXTIME(`d`.`servertime`),'%Y-%m-%d') = CURDATE()