gpt4 book ai didi

mysql - 插入表(var1) 从自身中选择

转载 作者:行者123 更新时间:2023-11-29 12:04:59 25 4
gpt4 key购买 nike

我想插入最后一列(该房间里的人数)并且我想使用

insert into table(n_people_in_room) 
select count(people_id)
from table
group by room

这显然是错误的,因为我需要在 people_id 上将表与其自身连接起来,但我没有。什么是正确的代码?

INPUT

OUTPUT

最佳答案

这是一种方法,使用内联 View 获取 N_People_In_Room 总数:

我首先将其作为选择:

 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

通过用 UPDATE 替换 SELECT ... FROM 并将其转换为 UPDATE,并添加 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

关于mysql - 插入表(var1) 从自身中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com