MySQL8.我看到查询中返回了一个伪行,因为缺少表名的规范。我知道怎么解决,我想知道为什么会这样。
请看以下小提琴:
http://sqlfiddle.com/#!9/beb1ed/1/0
其目的是在计划表中查找与subscriptionid和date匹配的任何行。
返回的结果是:

RealWorldVisitDate      CustomerID      SubscriptionID
2019-01-14 00:00:00     5               13
2019-01-14 00:00:00     17              23

但是where子句应该将结果限制在第一行(customerid 5/subscriptionid 13)。
我知道解决这个问题并返回正确行的方法是按照以下查询在where中指定表:
SELECT * FROM tblPlanned WHERE ( SELECT COUNT(1) FROM tblScheduled WHERE tblScheduled.SubscriptionID = **tblPlanned.**SubscriptionID AND tblScheduled.DateScheduled = RealWorldVisitDate ) > 0

但我想理解为什么原始查询(按照fiddle)返回customerid 17/subscriptionid 23的一个伪行,因为tblscheduled中不存在日期和subscriptionid组合的行。很明显,这与2个表中的subscriptionid列名重复有关,但我无法理解导致它的mysql执行逻辑。
(由于之前抱怨过多细节,这个问题故意简短。问我是否需要进一步的资料等)。
谢谢您。
按照fiddle的模式和数据:
CREATE TABLE `tblScheduled` (
  `ScheduledTargetID` bigint(20) NOT NULL,
  `DateScheduled` datetime NOT NULL,
  `CustomerID` int(10) UNSIGNED NOT NULL,
  `SubscriptionID` int(10) UNSIGNED NOT NULL
);

INSERT INTO `tblScheduled` (`ScheduledTargetID`, `DateScheduled`, `CustomerID`, `SubscriptionID`) VALUES
(25, '2018-11-19 00:00:00', 16, 15),
(24, '2018-11-19 00:00:00', 17, 23),
(27, '2018-11-23 00:00:00', 5, 1),
(26, '2018-11-23 00:00:00', 14, 18),
(23, '2019-01-14 00:00:00', 5, 13);

CREATE TABLE `tblPlanned` (
  `RealWorldVisitDate` datetime DEFAULT NULL,
  `CustomerID` int(10) UNSIGNED DEFAULT NULL,
  `SubscriptionID` int(10) UNSIGNED DEFAULT NULL
);

INSERT INTO `tblPlanned` (`RealWorldVisitDate`, `CustomerID`, `SubscriptionID`) VALUES
('2019-01-15 00:00:00', 5, 4),
('2019-01-14 00:00:00', 5, 13),
('2019-01-28 00:00:00', 5, 27),
('2019-01-14 00:00:00', 17, 23),
('2019-02-11 00:00:00', 17, 23);


SELECT * FROM tblPlanned WHERE ( SELECT COUNT(1) FROM tblScheduled WHERE tblScheduled.SubscriptionID = SubscriptionID AND tblScheduled.DateScheduled = RealWorldVisitDate ) > 0

最佳答案

mysql在子查询中查找列的默认位置是您正在查询的表,因此

SELECT COUNT(1)
FROM tblScheduled
WHERE tblScheduled.SubscriptionID = SubscriptionID AND tblScheduled.DateScheduled = RealWorldVisitDate

实际上与:
SELECT COUNT(1)
FROM tblScheduled
WHERE tblScheduled.SubscriptionID = tblScheduled.SubscriptionID AND tblScheduled.DateScheduled = RealWorldVisitDate

相当于
SELECT COUNT(1)
FROM tblScheduled
WHERE tblScheduled.DateScheduled = RealWorldVisitDate

这解释了您得到的结果,因为tblScheduledDateScheduled='2019-01-14 00:00:00'中的行与tblPlanned中的两行匹配(那些[CustomerID, SubscriptionID]=[5,13][17,23])。

09-25 20:34