/    Sign up×
Community /Pin to ProfileBookmark

MySql – copy column between tables

What would be the MYSQL command to copy contents of one column from one table into a column of another table if a certain condition is true?

For example..

Table t1
Column a
column b

Table t2
column c
column d

I’d like to copy a into c if b=d.

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@AneweraOct 31.2005 — //Web 101 - The would be an the INSERT SELECT.


$query = "INSERT INTO table2 (colA,col? SELECT colC,ColD FROM table1 WHERE colC = '$var'";
Copy linkTweet thisAlerts:
@chazzyOct 31.2005 — hi.

anewera's response is wrong, it depends on some external variable and copies both a and b. you only want to copy a into c if b=d.

first build your query to compare:

select b.colC from table a, table b where a.colB = b.colD

this gives you all of the b's that match up.

now we want to UPDATE, since the records already exist.

UPDATE tablea set colA = (select colC from tableb b where b.colD = tablea.col?

that should work.

it depends on B,D being defined as unique keys though.
×

Success!

Help @web101 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...