我有四张桌子:
CREATE TABLE `A` (
`AID` bigint(20) NOT NULL AUTO_INCREMENT,
`Name` varchar(150) DEFAULT NULL,
PRIMARY KEY (`AID`)
);
CREATE TABLE `B` (
`BID` bigint(20) NOT NULL AUTO_INCREMENT,
`DtStart` datetime DEFAULT NULL,
`DtStop` datetime DEFAULT NULL,
`AID` bigint(20) DEFAULT NULL,
`CID` bigint(20) DEFAULT NULL,
PRIMARY KEY (`BID`)
);
CREATE TABLE `C` (
`CID` bigint(20) NOT NULL AUTO_INCREMENT,
`FLAGS` smallint(6) DEFAULT NULL,
PRIMARY KEY (`CID`)
);
CREATE TABLE `D` (
`DID` bigint(20) NOT NULL AUTO_INCREMENT,
`CID` bigint(20) DEFAULT NULL,
`Name` varchar(150) DEFAULT NULL,
PRIMARY KEY (`DID`)
);
我正在提供这样的数据,
INSERT INTO A (Name) VALUES ("First");
INSERT INTO C (FLAGS) VALUES (1);
INSERT INTO B (DtStart, DtStop, AID, CID) VALUES ("2016-09-07", "2017-09-07", 1, 1);
INSERT INTO D (CID, Name) VALUES (1, "Alan");
INSERT INTO C (FLAGS) VALUES (2);
INSERT INTO B (DtStart, DtStop, AID, CID) VALUES ("2016-09-15", "2017-09-23", 1, 2);
INSERT INTO D (CID, Name) VALUES (2, "John");
当我点击查询时:
SELECT
A.Name as Object, B.DtStart, B.DtStop, C.FLAGS, D.Name as User
FROM A
LEFT JOIN B ON B.AID=A.AID
LEFT JOIN C ON C.CID=B.CID
LEFT JOIN D ON D.CID=C.CID
WHERE "2017-09-01" <= B.DtStop AND "2017-10-01" > B.DtStart;
我得到了结果:
+--------+---------------------+---------------------+-------+------+
| Object | DtStart | DtStop | FLAGS | User |
+--------+---------------------+---------------------+-------+------+
| First | 2016-09-07 00:00:00 | 2017-09-07 00:00:00 | 1 | Alan |
| First | 2016-09-15 00:00:00 | 2017-09-23 00:00:00 | 2 | John |
+--------+---------------------+---------------------+-------+------+
2 rows in set (0.00 sec)
我怎样才能找到包含给定日期范围间隙的所有行?
在我的示例中,我正在寻找报告( 2017年9月1日到 2017年9月30日),所以我想要这样的结果:
+--------+---------------------+---------------------+-------+------+
| Object | DtStart | DtStop | FLAGS | User |
+--------+---------------------+---------------------+-------+------+
| First | 2016-09-07 00:00:00 | 2017-09-07 00:00:00 | 1 | Alan |
| First | 2017-09-08 00:00:00 | 2017-09-14 00:00:00 | NULL | NULL |
| First | 2016-09-15 00:00:00 | 2017-09-23 00:00:00 | 2 | John |
| First | 2016-09-24 00:00:00 | 2017-09-30 00:00:00 | NULL | NULL |
+--------+---------------------+---------------------+-------+------+
4 rows in set (0.00 sec)
这只是我原始表的模型,我在查询中有10个表的多个连接