我有通过 sid 链接的学生表和事件表。
CREATE TABLE `students` (
`sid` int(8) NOT NULL COMMENT 'use',
`active` enum('Yes','No','vac','Grad') NOT NULL DEFAULT 'Yes',
`name` varchar(130) DEFAULT NULL,
`bus` varchar(130) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `students` (`sid`, `LEFT(name, 2)`, `bus`) VALUES
(51, 'Me', 'BusA'),
(52, 'Hi', 'BusA'),
(59, 'An', 'BusA'),
(70, 'Mi', 'BusB'),
(100, 'Yu', 'BusB');
CREATE TABLE `STATevent` (
`eventid` int(24) NOT NULL,
`sid` int(4) NOT NULL,
`date` datetime NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`level` enum('absent','bus') CHARACTER SET utf8 NOT NULL,
`color` varchar(10) NOT NULL,
`Percent` tinyint(5) NOT NULL,
`note` varchar(266) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `STATevent` (`eventid`, `sid`, `date`, `created`, `level`, `color`, `Percent`, `note`) VALUES
(43, 59, '2022-11-30 21:17:04', '2022-11-28 12:17:04', 'bus', 'red', 100, '');
学生可以选择不乘坐巴士服务,该服务显示为条目(如上面的 eventid 43)。我可以获得“公交车学生”的列表,以及显示谁取消了服务、谁没有取消服务的 ID。
SELECT C.name, C.sid, O.sid AS 'bid', C.bus FROM students C
LEFT JOIN STATevent O ON C.sid = O.sid
WHERE C.bus LIKE 'Bus%' AND C.active = 'Yes' ;
但是,当我尝试用日期限制地点时,结果仅显示取消服务的人。
SELECT C.name, C.sid, O.sid AS 'bid', C.bus FROM students C
LEFT JOIN STATevent O ON C.sid = O.sid
WHERE C.bus LIKE 'Bus%' AND C.active = 'Yes' AND O.date LIKE '2022-11-29%';
如何添加此限制器并获得像第一个查询一样的完整结果? 预先感谢您的帮助。
最佳答案
您可以将对事件日期的限制移至左连接的 ON
子句:
SELECT c.name, c.sid, o.sid AS bid, c.bus
FROM students c
LEFT JOIN STATevent o
ON o.sid = c.sid AND
DATE(o.date) = '2022-11-29'
WHERE c.bus LIKE 'Bus%' AND c.active = 'Yes';
对于没有取消服务的学生,出价
将被报告为空。
关于Mysql,显示谁选择了和没有选择退出巴士服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74610358/