gpt4 book ai didi

mysql - 在不使用联合的情况下插入具有默认值的多行

转载 作者:行者123 更新时间:2023-11-29 01:55:27 25 4
gpt4 key购买 nike

我使用此查询将多行插入到我的表 user 中。

 insert into user 
(select 'bbb', coalesce(max(subid),0)+1 from user where name = 'bbb')
union
(select 'ccc', coalesce(max(subid),0)+1 from user where name = 'ccc');

如何在单个 select 查询中获得相同的结果?

最佳答案

不完全是。问题是当名称不在表中时会发生什么。你可以这样做:

insert into user(name, subid)
select n.name, coalesce(max(u.subid), 1)
from (select 'bbb' as name union all select 'ccc') n left join
user u
on u.name = n.name
group by u.name;

它仍然有一个用于构造名称的union (all),但是subid的计算只表达了一次。

使用 insert 时,明确列出列是个好主意。

关于mysql - 在不使用联合的情况下插入具有默认值的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30353806/

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