开发者

MySQL Foreach row in table

Lets say I have two ta开发者_运维知识库bles: posts and tags. And I want to, via pure SQL, iterate through all posts with the posts.type set to user. With those post.id of those matched posts, I need co create a new tags with the given post.key for that row.

posts Table:
id
type

tags
id
post_key
name

So something like this (pseudo code):

FOREACH(SELECT post.id FROM posts WHERE post.type = 'user')
  INSERT INTO tags (post_key, name) VALUES (post.id, 'mytag')

Is this doable with SQL alone?


Sure. You can simply use an insert with a select statement from the other table. It is not the same logically as iterating over each row, but will get the same results (and perform much better)

Try:

INSERT INTO tags (post_key, name)
  SELECT post.id, 'mytag' 
  FROM posts
  WHERE post.type = 'user'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜