lundi 31 août 2015

How to update a table with values coming from another table?

I found similar ones at here, but not exactly the same.

Here is what I need:

I have two tables a and b, with the following structures:

Table a:

id  b_id    b_col2 b_col3 col5
1   NULL    NULL   NULL   NULL
2   XXX     XXX    XXX    XXX

Table b:

id    col2 col3
101   ABC  DEF
102   XXX  XXX

UPDATE: The goal is that with three given inputs (id, b_id, col5), one row of table a should be updated accordingly. Specifically, b_col2 and b_col3 are extracted from table b with that b.id = b_id. For example, I want to update the first item of a with b_id=101 and col5 = ZZZ. Notice that b_col2 = ABC and b_col3 = DEF in this case, the updated row should be:

id  b_id    b_col2 b_col3 col5
1   101     ABC    DEF    ZZZ

I know there is at least a not-so-effective way which I don't like:

update a set 
    a.b_id = some-id, 
    a.b_col2 = (SELECT col2 FROM b WHERE b.id = some-id),
    a.b_col3 = (SELECT col3 FROM b WHERE b.id = some-id),
    ...
    where a.`id` = xxx

As I said, this is not a very good method, and I am just wondering if there is any better method?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire