说,我有一张给定here的表格。该表具有以下结构(测试日,学生姓名和获得的标记)
D NAME MARKS
2001-01-01 a 1
2001-01-04 a 4
2001-01-06 a 3
2001-01-08 a 3
2001-01-01 b 1
2001-01-10 b 15
2001-01-01 c 1
2001-01-06 c 2
2001-01-08 c 5
2001-01-10 c 7
我想通过给那些没有参加每个考试的学生的0分来更新表格。更新表应该看起来像this
D NAME MARKS
2001-01-01 a 1
2001-01-02 a 0
2001-01-04 a 4
2001-01-06 a 3
2001-01-08 a 3
2001-01-02 a 0
2001-01-01 b 1
2001-01-02 b 0
2001-01-04 b 0
2001-01-06 b 0
2001-01-08 b 0
2001-01-10 b 15
2001-01-01 c 1
2001-01-02 c 2
2001-01-04 c 0
2001-01-06 c 0
2001-01-08 c 5
2001-01-10 c 7
到目前为止,我能想出的唯一解决方案(非常慢的查询)是:
SELECT DISTINCT(D) FROM tableA;
SELECT DISTINCT(NAME) FROM tableA;
使用PHP,在嵌套循环中进行SQL查询
INSERT IGNORE (D,NAME,MARKS)($D,$NAME,0);
然而,整个代码花费了太多时间(以分钟为单位),因为行数超过50k。
有什么更好的建议吗?
答案 0 :(得分:4)
可能会对可能的日期和可能的名称进行交叉连接,并且与当前结果保持联接: -
INSERT INTO A (D, name, marks)
SELECT Dates.D, Names.name, 0
FROM (SELECT DISTINCT D FROM A) Dates
CROSS JOIN (SELECT DISTINCT name FROM A) Names
LEFT OUTER JOIN A
ON Dates.D = A.D AND Names.name = A.name
WHERE A.name IS NULL
请注意,这确实假设每天至少有一个人有标记。
如果你有一个名字表和一个日期表,那就更好了,只是在表A中使用了这些行的ID
如果您想在一系列日期中执行此操作,即使当天没有人标记: -
INSERT INTO A (D, name, marks)
SELECT Dates.aDate, Names.name, 0
FROM
(
SELECT DATE_ADD('2001-01-01', INTERVAL units.i + tens.i * 10 + hundreds.i * 100 DAY) AS aDate
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) hundreds
HAVING aDate BETWEEN '2001-01-01' AND '2001-12-30'
) Dates
CROSS JOIN
(
SELECT DISTINCT name
FROM A
) Names
LEFT OUTER JOIN A
ON Dates.aDate = A.D AND Names.name = A.name
WHERE A.name IS NULL