如果表为空,执行INSERT吗? [英] Execute INSERT if table is empty?
本文介绍了如果表为空,执行INSERT吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以在计数条件下进行插入,例如:
Is there a way to do an insert under a count condition, something like:
INSERT INTO my_table (colname) VALUES('foo') IF COUNT(my_table) < 1
基本上,如果表当前为空,我想插入一个默认记录.我正在使用mysql.
Basically I want to insert a single default record if the table is currently empty. I'm using mysql.
推荐答案
使用SELECT而不是VALUES可以使用WHERE子句扩展查询.
Use SELECT instead of VALUES to be able to expand the query with a WHERE clause.
EXISTS是更好的&比COUNT更快的测试
EXISTS is a better & faster test than COUNT
INSERT INTO my_table (colname)
SELECT 'foo'
WHERE NOT EXISTS (SELECT * FROM my_table)
这篇关于如果表为空,执行INSERT吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文