我为调查软件创建了一个数据库。数据库的两个表是我想要做的,我想从两个日期范围和某个位置获取平均分数,并获得没有答案的零或为零或零。我尝试了
SELECT
AVG(tbAnswers.averageScore)
FROM
tbDrivers
LEFT JOIN tbAnswers ON tbDrivers.driverId = tbAnswers.driverId
WHERE
tbDrivers.place = 'WDC'
GROUP BY
tbDrivers.driverId
但是当我指定日期范围时,没有答案就无法获取驱动程序的数据。
SELECT AVG(tbAnswers.averageScore)
FROM tbDrivers LEFT JOIN tbAnswers ON tbDrivers.driverId = tbAnswers.driverId
WHERE tbDrivers.place = 'WDC'
AND answerDate BETWEEN '2018-11-28' AND '2018-12-03'
GROUP BY tbDrivers.driverId
CREATE TABLE `tbAnswers` (
`answerId` int(11) NOT NULL,
`answerDate` date NOT NULL,
`driverId` int(11) NOT NULL,
`score1` int(11) NOT NULL,
`score2` int(11) NOT NULL,
`score3` int(11) NOT NULL,
`averageScore` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tbAnswers` (`answerId`, `answerDate`, `driverId`, `score1`, `score2`, `score3`, `averageScore`) VALUES
(10, '2018-11-28', 1032, 0, 0, 0, 0),
(11, '2018-11-29', 1032, 9, 8, 3, 6.67),
(12, '2018-11-30', 1032, 0, 3, 2, 1.67),
(13, '2018-11-30', 1035, 10, 2, 10, 7.34),
(14, '2018-11-01', 1032, 5, 5, 5, 5),
(15, '2018-12-03', 1035, 5, 5, 7, 5.67);
CREATE TABLE `tbDrivers` (
`driverId` int(11) NOT NULL,
`nameSurname` varchar(32) NOT NULL,
`place` varchar(64) NOT NULL,
`plate` varchar(8) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tbDrivers` (`driverId`, `nameSurname`, `place`, `plate`) VALUES
(1032, 'Nick Oliver', 'WDC', 'B16186D'),
(1033, 'Nicholas Keller', 'WDC', 'ACG8095'),
(1034, 'Felipe Mendez', 'WDC', 'C26106E'),
(1035, 'Lowell Butler', 'WDC', '5123QK');
我该如何解决这个问题?
答案 0 :(得分:1)
使用查询来获取至少有一个答案的驱动程序,UNION
没有答案的驱动程序:
(SELECT tbDrivers.driverId, AVG(tbAnswers.averageScore) AS avgscore
FROM tbDrivers LEFT JOIN tbAnswers ON tbDrivers.driverId = tbAnswers.driverId
WHERE tbDrivers.place = 'WDC'
AND answerDate BETWEEN '2018-11-28' AND '2018-12-03'
GROUP BY tbDrivers.driverId )
UNION
(SELECT t.driverId, NULL AS avgscore
FROM tbDrivers t
WHERE
NOT EXISTS (SELECT 1 FROM tbAnswers WHERE tbAnswers.driverId = t.driverId))
ORDER BY driverId
结果是:
driverId avgscore
1032 2.7800000111262
1033 (null)
1034 (null)
1035 6.505000114440918
答案 1 :(得分:1)
出现问题是因为在tbanswers表中没有关于driverid的记录。
要么在tbanswers中输入条目,要么使用上面Forpas给出的查询或使用该查询
SELECT tbdrivers.driverid,
Avg(tbanswers.averagescore)
FROM tbdrivers
LEFT JOIN tbanswers
ON tbdrivers.driverid = tbanswers.driverid
WHERE tbdrivers.place = 'WDC'
AND answerdate BETWEEN '2018-11-28' AND '2018-12-03'
OR answerdate IS NULL
GROUP BY tbdrivers.driverid