从查询的结果集更新另一个表

时间:2012-09-13 13:21:12

标签: mysql stored-procedures count sql-update

select 
(SELECT count(ts.student_id) AS studentcount
from tb_student ts
where  ts.tudent_id>101 )as count1,
(SELECT count(tt.teacher_id) AS Totalteacher from tb_teacher tt
 where feedback_id<>0) as count2

这给了我一些结果

count1   count2
 4         9

在某些情况下,计数将等于

 count1   count2
 9         9

我需要使用此结果更新另一个表,例如count1=count2时  然后更新名为tb_log的表并设置falg=1

除了通过程序执行此操作外,是否可以在此查询中完成。

1 个答案:

答案 0 :(得分:0)

这可以很容易地完成:

update tb_log
    set falg = 1
    where exists (select count1, count2
                  from (SELECT count(ts.student_id) AS studentcount
                        from tb_student ts
                        where  ts.tudent_id>101
                       ) as count1 cross join
                       (SELECT count(tt.teacher_id) AS Totalteacher
                        from tb_teacher tt
                        where feedback_id<>0
                       ) as count2
                  where count1 = count2
                 )

我将子查询从SELECT子句移动到FROM子句中。我认为当表引用在FROM子句中时,查询更容易理解。这也使得在WHERE子句中应用条件变得更容易。