用一个等效查询替换两个查询

时间:2017-03-08 10:48:19

标签: mysql sql sql-update

这两个查询(工作正常)可以替换为一个吗?

INSERT INTO temptable 
(
    `id`,`aggr`
)
select a.id, b.aggr
from main a
inner join  (
  select uk, group_concat(cascina_uk SEPARATOR '|') as aggr
  from main 
  group by  uk 
) b on a.uk = b.uk;

update main, temptable set main.aggr = temptable.aggr where main.id=temptable.id;

我不需要创建临时表。我只需要更新main.aggr列。

3 个答案:

答案 0 :(得分:1)

从您的查询中我了解到您要更新具有相同值id的多个aggr行。然后这个应该工作:

update main
set aggr = group_concat(cascina_uk SEPARATOR '|')
group by uk

答案 1 :(得分:1)

试试这个

update main c
set 
  c.aggr = (select b.aggr 
               from 
                   main a,
                   (select uk, group_concat(cascina_uk SEPARATOR '|') as aggr from main group by uk ) b
               where 
                 a.uk = b.uk
                 and c.id = a.id)

答案 2 :(得分:1)

使用MySQL的多表更新语法:

update main, (
    select a.id, b.aggr
    from main a
    join (
        select uk, group_concat(cascina_uk SEPARATOR '|') as aggr
        from main 
        group by uk 
    ) b on a.uk = b.uk
) temptable
set main.aggr = temptable.aggr
where main.id = temptable.id

请注意,我只将将查询的部分重新排列到一个工作查询中;我怀疑可以对子查询进行优化。