gpt4 book ai didi

MySQL IF 语句检查表是否为空

转载 作者:行者123 更新时间:2023-11-29 22:29:24 26 4
gpt4 key购买 nike

如何创建 IF 语句,以便在发现表为空时插入默认行?我遵循这个逻辑,但有些地方是错误的。

IF ((SELECT * FROM myTable)=0)
THEN
INSERT INTO myTable
(myColumn) VALUES (myValue)
END IF;

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

评论中的回答(McAdam331)http://sqlfiddle.com/#!9/42229/1

CREATE TABLE myTable(
name VARCHAR(100));

INSERT INTO myTable (`name`)
SELECT 'namer'
FROM DUAL
WHERE NOT EXISTS (SELECT * FROM myTable);

最佳答案

你可以使用这样的东西:

/* Insert query */
INSERT INTO myTable (
/* You place the values in the 'FROM' part of this query */
SELECT tbl.*
FROM ( SELECT 1 AS id, 'username' AS username, 'password' AS password ) AS tbl
WHERE 0 = (SELECT COUNT(*) FROM myTable )
);

它以 INSERT 部分开头。之后是一个子查询来选择“记录”(您可以在 FROM ( SELECT ... 部分中给出值)。where 确保当前不存在记录时仅进行插入。

关于MySQL IF 语句检查表是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29945590/

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