简体   繁体   中英

How to Copy Column data from one table to another table in MySql?

I have two tables

  1. users
  2. activity

I have a column in the users table which is named as activity_date . Now, I want to add that column's data to my Activity table. For this, I introduce a new field in the Activity table named activity_date .

I am using this query to copy data from users table to activity table

DB::statement('UPDATE `activity` (`activity_date`) SELECT `activity_date` FROM `users` WHERE `users.id` = `activity.user_id`');

When I run the migration, It returns an error

[PDOException]                                                                      
SQLSTATE[233652]: Column not found: 1054 Unknown column 'users.id' in 'where clause'  

I never tried this before. May someone please guide me on how to do this? Where I am doing wrong?

you should join your tables then use DB::raw

DB::table('activity')->join('users','activity.user_id','=','users.id')
        ->update(['activity.activity_date'=>DB::raw('users.activity_date')]);
update users set activity_date=(SELECT activity_date from activity where id='1')where id='1'

This will take acitivity_date with ID=1 from table activity, and update acitivity_date in users table where user id=1.

tables: (users): id, name, activity_date (activity) id, activity_date

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