使用SELECT查询的结果作为INSERT查询中的值

时间:2016-05-18 16:23:47

标签: mysql sql

是否可以将查询结果用作INSERT查询中字段的值?这是我想要实现的目标,但我是以正确的方式进行的吗?

INSERT INTO tblCounts ( CategoryID, GroupID, CountNo )
VALUES (DMAX("CategoryID","tblCategories"), (SELECT GroupID from tblGroups), 0);

1 个答案:

答案 0 :(得分:1)

你应该用这个:

INSERT INTO tblCounts ( CategoryID, GroupID, CountNo )
select DMAX("CategoryID","tblCategories"), GroupID, 0
from tblGroups;

但似乎DMAXAccess function,而不是MySQL

对于CountNo为3且CategoryID为2的条件,您应该在select查询中添加where子句,如下所示:

INSERT INTO tblCounts ( CategoryID, GroupID, CountNo )
select DMAX("CategoryID","tblCategories"), GroupID, 0  -- select 2, GroupID, 3 from tblgroups where CategoryID = 2 and CountNo = 3--?
from tblGroups
where CategoryID = 2 and CountNo = 3;