単一の SQL ステートメントでブログ投稿にタグを追加したいと思います。
私のテーブルは次のようになります。
tags
+-------+-----------+
| tagid | tag |
+-------+-----------+
| 1 | news |
| 2 | top-story |
+-------+-----------+
tag2post
+----+--------+-------+
| id | postid | tagid |
+----+--------+-------+
| 0 | 322 | 1 |
+----+--------+-------+
私が解決したい問題は、新しいタグを挿入し、そのIDを取得してから、この新しい ID を単一の SQL ステートメントでリレーション テーブルに挿入することです。
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'
)
)