简体   繁体   中英

Update multiple MySQL rows from another table

Ok I have two tables: articles and posts.

In articles, I have the "image" column where each entry has a name for the image.

In the posts table, I have the "post_image" column where I want to put all the values from the articles table, with the matching article id.

This is what I'm trying to do but of course it spits out an error since it's more than one value. I know it should be a JOIN but I get lost with joins. Any help?

UPDATE posts SET post_image = (
SELECT image FROM articles, posts WHERE article_id = ID
)

I tried this:

UPDATE posts SET post_image = (SELECT image FROM articles WHERE article_id = ID LIMIT 1)

And all it does is update all the entries of "post_image" with the first value of "articles".

Actually, I was doing the wrong thing, it was much simpler than that. Here's what finally worked for me:

UPDATE posts, articles
SET posts.post_image = articles.image
WHERE posts.ID = articles.article_id

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM