1

我目前正在使用以下查询来确定数据库中的哪些项目没有关联的里程碑:

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

我现在如何INSERT为该表中的每个 project_id 设置一个新的里程碑行?

4

1 回答 1

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
于 2012-08-05T14:13:27.697 回答