I'm making a blog site and I need to check if a tag exists before inserting the tag into the tblTag
This is what I'm trying:
$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
";
But is not working correctly, can anybody lend me some assistance here?? Where am i going wrong, this seems fairly straight forward SQL.
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'));
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] ... ]
Is the tagId a primary key? If yes, you need not to insert '' or a null value to it. If not try setting it as a primary key and enable its auto incerement so you just need to supply for the tagName I'm pretty sure it really is straight forward. So you should just check if all insert items have values or available for the insert query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.