用于检查表是否为空的MySQL IF语句

时间:2015-04-29 13:43:34

标签: mysql

如果发现表为空,如何创建将插入默认行的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);

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

/* 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 ...部分给出值。如果当前没有记录,那么确保只有插入。

答案 1 :(得分:0)

http://sqlfiddle.com/#!2/ba9ed/1

INSERT INTO table1 (myColumn)
  SELECT 
    'myValue' 
  FROM (
    SELECT COUNT(*) c 
    FROM table1 t
    HAVING c=0) t2;