SQL Query从select查询的输出插入特定列

时间:2015-09-29 23:27:11

标签: mysql

我有一个查询,如下所示:

select department as departmentname,count(distinct(uid)) as userscnt 
from outlier_report where department is not null group by department ;

我想将此插入到已填充的outlier_output表中,并且包含大约20个字段,包括departmentname和user_count(此字段为空)。 我想将selectc输出中的userscnt字段放入outlier_output表中,其中department = outlier_report.departmentment_name

我假设它会是这样的:

Insert into outlier_output(user_count Select department, count(distinct(uid) as userscnt from outlier_report where the department=outlier_report.departmentment_name)

确切的查询将如何? 提前致谢

4 个答案:

答案 0 :(得分:0)

标准插入选择格式为:

INSERT INTO `tableA` ([field_list])
SELECT [results corresponding to items in the field list in the same order as the field list]
[etc...]

http://dev.mysql.com/doc/refman/5.6/en/insert.html

答案 1 :(得分:0)

这是查询语法的工作方式:

int array[4];

答案 2 :(得分:0)

我看到Particular columnwhere the department = outlier_report.department_name 所以我想,你想要UPDATE而不是INSERT。

请试试这个:

update outlier_output a
inner join (
    select department as departmentname,
    count(distinct(uid)) as userscnt 
    from outlier_report 
    where department is not null 
    group by department 
) b on a.department = b.departmentname
set a.user_count = b.userscnt 

这是针对INSERT的

insert into outlier_output  (department,user_count)
select department as departmentname,
count(distinct(uid)) as userscnt 
from outlier_report 
where department is not null 
group by department 

答案 3 :(得分:0)

您已经填充了它们,因此不需要INSERT。您只需要更新表中的user_count列。

UPDATE outlier_output a set 
    a.user_count=(select count(distinct(b.uid)) 
                         from outlier_report b 
                  where b.department=a.departmentname );