TransWikia.com

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

Stack Overflow Asked on December 11, 2021

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?

2 Answers

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

Answered by Eryngium on December 11, 2021

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')]);

Answered by OMR on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP