我整天都在纠缠这个问题。我在这里发帖,希望有人能帮助我。
我试图通过添加它们来修复缺少值的数据库。
我们说我们有以下表格:
Color with columns (itemId, colorId)
Process with columns (itemId, colorId, iteration, rating)
仅当评级大于0时,进程才包含条目。我想通过为每次迭代添加评级== 0的缺失条目来解决这个问题。
例如,表进程包含:
item id | color id | iteration | rating
1 | 1 | 1 | 1
1 | 1 | 2 | 2
1 | 1 | 3 | 2
1 | 2 | 3 | 1
1 | 1 | 4 | 5
1 | 2 | 4 | 5
缺少的条目是:
item id | color id | iteration | rating
1 | 2 | 1 | 0
1 | 2 | 2 | 0
我是SQL的初学者,并不熟悉联接。我正在考虑使用插入选择组合与连接。也许是交叉加入?
非常感谢您的帮助!非常感谢!
PS:我使用的是mysql,但我想这不会影响答案。
编辑:感谢您提出的解决方案。但是它们都不起作用,因为假设列迭代没有缺失值。但是,对我来说就是这样。请考虑"迭代"作为另一个id,不是必要的增量......所以我真正想要的是,只要表过程中有一个条目用于给定的itemId和迭代,那么每个colorId也有一个条目(在表Color中匹配itemId)。此缺失条目的评级应为0.
答案 0 :(得分:3)
SELECT
P.itemId
,C.colorId
,I.iteration
,0 AS rating
FROM
(SELECT DISTINCT itemId FROM Process) P
CROSS JOIN
(SELECT DISTINCT colorId FROM Color) C
CROSS JOIN
(SELECT DISTINCT iteration FROM Process) I
LEFT JOIN
Process E
ON P.itemId = E.itemId
AND C.colorId = E.colorId
AND I.iteration = E.iteration
WHERE E.rating IS NULL
答案 1 :(得分:2)
Updated
INSERT INTO process (itemId, colorId, iteration, rating)
SELECT p1.itemId, p1.colorId, i.iteration, 0
FROM (SELECT itemId, colorId, MAX(iteration) as max_iteration
FROM process
GROUP BY itemId, colorId
) p1
INNER
JOIN (SELECT DISTINCT iteration FROM process) i
ON i.iteration < p1.max_iteration
LEFT OUTER
JOIN process p2
ON p2.itemId = p1.itemId
AND p2.colorId = p1.colorId
AND p2.iteration = i.iteration
WHERE p2.iteration IS NULL;
答案 2 :(得分:1)
INSERT INTO Process (item,color,iteration,rating)
SELECT C.item, C.color, I.iteration, 0 FROM Color C
CROSS JOIN (SELECT DISTINCT iteration FROM Process) I
LEFT JOIN Process P
ON P.item=C.item AND P.color=C.color AND P.iteration=I.iteration
WHERE P.rating IS NULL