我想用一个sql语句在博客帖子中添加一个标签.
说我的表看起来如下:
tags
+-------+-----------+
| tagid | tag |
+-------+-----------+
| 1 | news |
| 2 | top-story |
+-------+-----------+
tag2post
+----+--------+-------+
| id | postid | tagid |
+----+--------+-------+
| 0 | 322 | 1 |
+----+--------+-------+
我想解决的问题是插入一个新标签,检索它的id,然后在一个sql语句中将这个新id插入到关系表中.
INSERT INTO tag2post (postid, tagid)
VALUES
(
332, # the post
IF (
(SELECT tagid FROM tags WHERE tag = 'new_tag'),
(SELECT tagid FROM tags WHERE tag = 'new_tag'),
# here is where i'd like to insert
# the new_tag and return it's id
'i am lost here'
)
)
解决方法:
您不能将此作为单个插入执行,因为插入是原子的 – 也就是说,在语句完成之前不会确定ID.
在事务中包装两个语句,您将获得您的ID和原子性.