因此,这实际上可以根据需要发挥作用,但在使用数百个问题进行百万次测试等全面测试时可能会出现性能问题。
我是一个SQL新手,所以任何有关如何做得更好的性能提示或架构建议都将不胜感激。非常感谢。
希望这个SQL Fiddle链接可以正常工作:http://sqlfiddle.com/#!9/ef8ef/1
-- Get last test score of the day for each day.
CREATE TABLE tests (
id INT(10) unsigned NOT NULL AUTO_INCREMENT,
user_key CHAR(32) COLLATE utf8mb4_unicode_ci NOT NULL,
q1_answer TINYINT(3) unsigned NOT NULL,
q2_answer TINYINT(3) unsigned NOT NULL,
date_taken timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO tests VALUES
(DEFAULT, '007userkey', 11, 33, '2016-01-10 16:01:01'),
(DEFAULT, '007userkey', 3, 55, '2016-01-10 19:01:01'),
(DEFAULT, '007userkey', 100, 44, '2017-03-03 12:01:01'),
(DEFAULT, '007userkey', 37, 66, '2017-06-10 15:01:01'),
(DEFAULT, '007userkey', 96, 77, '2017-06-10 20:12:01'),
(DEFAULT, '007userkey', 6, 99, '2017-06-10 20:13:01'),
(DEFAULT, '007userkey', 2, 22, '2017-09-12 00:01:01');
-- Works, but all this for each test question?
-- Question #1
SELECT DATE_FORMAT(t1.date_taken, '%Y-%m-%d') AS date,
t1.q1_answer AS q1score
FROM (
SELECT MAX(date_taken) AS maxval
FROM tests
WHERE user_key = '007userkey'
GROUP BY DATE_FORMAT(date_taken, '%Y-%m-%d')
) AS t2
INNER JOIN tests AS t1
ON t1.date_taken = t2.maxval
ORDER BY DATE_FORMAT(date_taken, '%Y-%m-%d') ASC;
-- Question #2
SELECT DATE_FORMAT(t1.date_taken, '%Y-%m-%d') AS date,
t1.q2_answer AS q2score
FROM (
SELECT MAX(date_taken) AS maxval
FROM tests
WHERE user_key = '007userkey'
GROUP BY DATE_FORMAT(date_taken, '%Y-%m-%d')
) AS t2
INNER JOIN tests AS t1
ON t1.date_taken = t2.maxval
ORDER BY DATE_FORMAT(date_taken, '%Y-%m-%d') ASC;
此示例的所需结果(如SQL Fiddle中所示)将包含每天每个测试的最新或最后得分,格式如下:
date q1score
2016-01-10 3
2017-03-03 100
2017-06-10 6
2017-09-12 2
date q2score
2016-01-10 55
2017-03-03 44
2017-06-10 99
2017-09-12 22
仅供参考... PHP将使用此功能为每个问题制作基于JSON的图表,类似于:
"q1scores":[{"day_taken":"2017-09-04","score":100},{"day_taken":"2017-09-10","score":100}]
"q2scores":[{"day_taken":"2017-09-04","score":100},{"day_taken":"2017-09-10","score":100}]