插入表(var1)从中选择

时间:2015-07-27 21:41:49

标签: mysql

我想插入最后一栏(那个房间里的人数)和 我想用

Nc

这显然是错误的,因为我需要在people_id上​​加入表格,但我没有。什么是正确的代码?

INPUT

OUTPUT

1 个答案:

答案 0 :(得分:1)

以下是一种方法,使用内联视图获取N_People_In_Room总数:

我首先选择SELECT:

 SELECT t.peopleid
      , t.room
      , t.n_people_in_room AS `old_npir`
      , s.n_people_in_room AS `new_npir` 
  FROM mytable t
   JOIN ( SELECT c.room
               , COUNT(1) AS n_people_in_room
            FROM mytable c
           GROUP BY c.room
        ) s
     ON s.room = t.room

通过将SELECT ... FROMUPDATE重新合并,并添加SET条款,将其转换为更新...

 UPDATE mytable t
   JOIN ( SELECT c.room
               , COUNT(1) AS n_people_in_room
            FROM mytable c
           GROUP BY c.room
        ) s
     ON s.room = t.room
    SET t.n_people_in_room = s.n_people_in_room