gpt4 book ai didi

MySQL使用SELECT FROM DUAL WHERE NOT EXISTS将多行插入到空表中

转载 作者:行者123 更新时间:2023-11-29 07:38:18 25 4
gpt4 key购买 nike

如果表肯定是空的,我将使用此代码插入默认行。我试图扩展它以插入多行,但无法弄清楚语法:

INSERT INTO myTable(`myCol`)
SELECT 'myVal'
FROM DUAL
WHERE NOT EXISTS (SELECT * FROM myTable);
<小时/>

我得到了什么(@Uueerdo)

CREATE TEMPORARY TABLE `myDefaults` ( name VARCHAR(100) NULL DEFAULT NULL);# MySQL returned an empty result set (i.e. zero rows).

INSERT INTO myDefaults (name) VALUES ('a'), ('b');# 2 rows affected.


SET @valCount := 0;# MySQL returned an empty result set (i.e. zero rows).

SELECT COUNT(1) INTO @valCount FROM blsf;# 1 row affected.


INSERT INTO blsf(name)
SELECT name
FROM myDefaults
WHERE @valCount > 0;# MySQL returned an empty result set (i.e. zero rows).


DROP TEMPORARY TABLE `myDefaults`;# MySQL returned an empty result set (i.e. zero rows).

最佳答案

这样的事情应该有效:

CREATE TEMPORARY TABLE `myDefaults` ( the_value INT|VARCHAR|whatever... )
;
INSERT INTO myDefaults (the_value) VALUES (myVal1), (myVal2), ....
;

SET @valCount := 0; -- Because I am paranoid ;)
SELECT COUNT(1) INTO @valCount FROM myTable;

INSERT INTO myTable(myCol)
SELECT the_value
FROM myDefaults
WHERE @valCount = 0
;

DROP TEMPORARY TABLE `myDefaults`;

关于MySQL使用SELECT FROM DUAL WHERE NOT EXISTS将多行插入到空表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950912/

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