我目前正在使用以下查询来确定数据库中哪些项目没有关联的里程碑:
SELECT P.project_id, COUNT(M.milestone_id) as count FROM projects P
LEFT JOIN milestones M USING(project_id)
GROUP BY P.project_id
HAVING count < 1
然后它返回:
project count
---------------
9 0
34 0
32 0
41 0
我现在如何为该表中的每个project_id转到INSERT
一个新的里程碑行?
答案 0 :(得分:3)
您可以使用INSERT...SELECT
声明
INSERT INTO tableName (project_ID)
SELECT P.project_id
FROM projects P
LEFT JOIN milestones M
USING(project_id)
GROUP BY P.project_id
HAVING count < 1
将tableNAme
更改为要插入新行的表的名称。
更新1
INSERT INTO tableName (project_ID, colA, colB, colC)
SELECT P.project_id, colA, colB, colC
FROM projects P
LEFT JOIN milestones M
USING(project_id)
GROUP BY P.project_id
HAVING count < 1
现在问题出现了,如果你想要一个列中没有的值怎么办?你可以为它创建虚拟值。
INSERT INTO tableName (project_ID, field1, field2, field3)
SELECT P.project_id, '' AS field1, 0 AS field2, NULL AS field3
FROM projects P
LEFT JOIN milestones M
USING(project_id)
GROUP BY P.project_id
HAVING count < 1