如何记录是否存在,如何不插入 [英] How to check if record exists, if not insert
本文介绍了如何记录是否存在,如何不插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在建立一个博客网站,我需要在将标签插入tblTag之前检查标签是否存在
I'm making a blog site and I need to check if a tag exists before inserting the tag into the tblTag
这就是我正在尝试的:
$var_sqlTagsCheck = "IF (EXISTS(SELECT * FROM tblTag t WHERE t.tagName = '$var_tagCollectInsert'))
BEGIN
INSERT IGNORE INTO tblTag
SET tagName = '$var_tagCollectInsert'
END
ELSE
BEGIN
INSERT INTO tblTag (tagId, tagName) VALUES ('', '$var_tagCollectInsert'))
END
";
但是工作不正常,有人可以借给我一些帮助吗?哪里出错了,这似乎是相当直接的SQL。
But is not working correctly, can anybody lend me some assistance here?? Where am i going wrong, this seems fairly straight forward SQL.
推荐答案
尝试使用 EXISTS 谓词在 WHERE 子句中:
Try using the EXISTS predicate in the WHERE clause:
INSERT INTO tblTag (tagId, tagName)
SELECT '', '$var_tagCollectInsert'
WHERE NOT EXISTS(SELECT * FROM tblTag t
WHERE t.tagName = '$var_tagCollectInsert'));
MySQL的 INSERT INTO 的一般形式是:
The general form of MySQL's INSERT INTO is:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
这篇关于如何记录是否存在,如何不插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文