1

我们有 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

4

2 回答 2

1

与 B2 的左连接返回在 B1 之后发生的训练,这就是为什么如果不存在 ( B2.driverID is null) 你确定 B1 的训练是最后一个。

于 2013-02-14T18:35:55.237 回答
1

试试这个,更改'123'驱动程序ID:

select d.*,t.* 
from driver as d
inner join dtraining as t
on d.driverId=t.driverId
where d.driverid in (1,2,3,4.......10000)
order by t.driverTrainingDate desc
limit 1
于 2013-02-14T21:01:39.070 回答