同一列中的不同值,不同列中的输出

时间:2015-10-06 13:27:54

标签: mysql

目前我正在开展一个与一级方程式有关的项目。

这是我的结果表结构。

CREATE TABLE IF NOT EXISTS `races_results` (
  `resultid` int(11) NOT NULL,
  `seasonyear` int(4) NOT NULL,
  `trackid` tinyint(2) NOT NULL,
  `raceid` int(2) NOT NULL,
  `session` tinyint(1) NOT NULL,
  `q` int(11) NOT NULL,
  `place` tinyint(2) NOT NULL,
  `driverid` int(2) NOT NULL,
  `teamid` int(2) NOT NULL,
  `time` int(11) NOT NULL,
  `laps` int(2) NOT NULL,
  `status` varchar(3) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

我的大问题是我没有按照自己的意愿获得输出结果。

SELECT place, driverid, teamid, if(q=1, time, '') as time1, if(q=2, time, '') as time2, if(q=3, time, '') as time3 
FROM `races_results` 
WHERE `seasonyear` = 2015 AND `raceid` = 3 AND `session` = 2 AND `q` IN (1,2,3) 
GROUP BY driverid 
ORDER BY CASE WHEN q = 3 THEN place >= 1 AND place <= 10 END ASC, CASE WHEN q = 2 THEN place >= 11 AND place <= 16 END ASC, CASE WHEN q = 1 THEN place >= 17 AND place <= 22 END ASC

我的目标是,我希望驱动程序的所有时间都能并排显示,然后由各部门的参与者订购。

在此之后我应该有这样的输出http://www.formula1.com/content/fom-website/en/championship/results/2015-race-results/2015-japan-results/qualifying.html

1 个答案:

答案 0 :(得分:0)

根据您的问题,我了解表races_results对每个结果都有一行,因此不同资格的时间在不同的行上。要在一行中获取这些内容,您可以连接同一个表:

SELECT place, driverid, teamid, r1.time as time1, r2.time as time2, r3.time as time3
FROM races_results r1 LEFT JOIN races_results r2 on (r1.driverid=r2.driverid and r1.raceid=r2.raceid)
LEFT JOIN races_results r3 on (r1.driverid=r3.driverid and r1.raceid=r3.raceid)
WHERE r1.q=1 AND r2.q=2 AND r3.q=3 AND
`seasonyear` = 2015 AND `raceid` = 3 AND `session` = 2 
GROUP BY driverid 
ORDER BY place;

我假设:

  • 总是有q = 1的结果;
  • driveridraceid对于特定年份的参赛者来说是独一无二的;
  • 您想按地点订购。