表1
id count_2
1   0
2   0表2
id id1
1  1
2  1
3  2
4   2
5   2
求个更新语句使得表1变成
1  2
2  3
也就是说表2 的id1关联表1的id
表1中的count_2 就是 表2中的count后的值

解决方案 »

  1.   

    update tb1,(select id1,count(*) as num
    from tb2
    group id1
    )tb3
    set tb1.count_2=tb3.num 
    where tb1.id = tb3.id
      

  2.   


    如果我希望 在tb2中没有的 tb1的count_2,能被更新成0 怎么办?这个sql只能跟新掉两表有关联的。
      

  3.   

    (select id1,count(*) as num
    from tb2
    group id1
    )tb3这一段是什么意思?还有我试验了一下,报错
    Error Code: 1054. Unknown column 'tb3.id' in 'where clause'
      

  4.   

    update tb1 LEFT JOIN (select id1,count(*) as num
    from tb2
    group id1
    )tb3 ON tb1.id = tb3.id1
    set tb1.count_2=IFNULL(tb3.num,0)