我们有 2 张桌子,一张是包含所有驱动程序详细信息的驱动程序,桌子是 dTraining。
驱动程序的结构是
CREATE TABLE IF NOT EXISTS `driver` (
`driverID` int(5) NOT NULL,
`clientID` int(5) NOT NULL,
`driverName` varchar(100) NOT NULL,
`driverDateOfBirth` date NOT NULL,
`driverStatus` enum('a','d','i') NOT NULL DEFAULT 'a'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
dTraining 的结构是
CREATE TABLE IF NOT EXISTS `dTraining` (
`dTrainingID` int(5) NOT NULL,
`cTrainingID` int(5) NOT NULL,
`trainingID` int(11) NOT NULL,
`driverID` int(5) NOT NULL,
`clientID` int(5) NOT NULL,
`driverTrainingDate` date NOT NULL,
`driverTrainingUpdateStatus` enum('d','a') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我需要的是,当我运行这样的查询时,应该从驾驶员拥有的许多训练数据中给出最新的训练。所以我需要关于如何在那里运行子查询的帮助。
SELECT driver.driverID,dTraining.driverTrainingDate
FROM driver,dTraining
目前我有这个查询。样本输出将是
driverID=1 , driverTrainingDate=2013-02-01
driverID=2 , driverTrainingDate=2013-02-02
SELECT driver.driverID,b.driverTrainingDate
FROM driver
LEFT JOIN (
SELECT B1.*
FROM dTraining AS B1
LEFT JOIN dTraining AS B2
ON B1.driverID = B2.driverID
AND B1.cTrainingID = B2.cTrainingID
AND B1.driverTrainingDate< B2.driverTrainingDate
WHERE B1.cTrainingID =".$cTID." And B2.driverID IS NULL) as b
ON ( driver.driverID= b.driverID)
我很好奇为什么我们需要放置 B1.driverTrainingDate< B2.driverTrainingDate 而不是 B1.driverTrainingDate> B2.driverTrainingDate 并且需要 B2.driverID IS NULL