使用查询A的输出作为查询B的条件

时间:2012-08-05 14:07:59

标签: mysql database

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

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一个新的里程碑行?

1 个答案:

答案 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