开发者

MySQL: Loop over all entries to update parent table

开发者 https://www.devze.com 2023-02-06 23:18 出处:网络
I have a parent table \"user\" and a child table \"profile\". For every profile there also exists a user with the same id, but not the other way round. profiles have names, and now I added the propert

I have a parent table "user" and a child table "profile". For every profile there also exists a user with the same id, but not the other way round. profiles have names, and now I added the property name also to users.

I would like to fire an MySQL-Statements that loops over all profiles, grabs the user with the same id, and updates the column name of the user开发者_Python百科, with the name of the profile.

How can I do that? I never used loops in an SQL-Statement before..


@KenDowns was right, you dont need forloops. But his statement had a small flaw. Here is the correct one, that worked for me (you dont need a from-clause):

UPDATE user, profile
SET user.name = profile.name
WHERE profile.id = user.id


SQL is set-based and does not require loops for things like this:

UPDATE profiles
   set name = user.name
  from user
 where profiles.userId = user.userId
0

精彩评论

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

关注公众号