Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql double data on query

Tags:

mysql

I have data on 2 tables, like this

Table 1
no|   name  |  address |
1 | alex    |  br st   | 
2 | ujang   |  cilala  |
3 | adu     |  lind st |
4 | ujang   |  bilila  |
5 | ujang   |  gea     |

Table 2
no|   name  |  address |
1 | alex    |          |
2 | ujang   |          |
3 | adu     |          |
4 | adu     |          |

My Query is like this

UPDATE TABLE1 a 
JOIN TABLE2 b ON a.name = b.name
SET a.address = b.address

Result that i want

 Table 2
    no|   name  |  address |
    1 | alex    |  br st   |
    2 | ujang   |  cilala  |
    3 | adu     |  lind st |
    4 | adu     |  lind st |

That all i don't have word to say, i'am freeze.

like image 357
Sae Avatar asked Dec 31 '25 02:12

Sae


1 Answers

The following query updates TABLE2 using a temporary table containing only records from TABLE1 with the minimum no value, in cases where a name may occur more than once in TABLE1.

UPDATE TABLE2 a
INNER JOIN
(
    SELECT t1.no, t1.name, t1.address
    FROM TABLE1 t1
    INNER JOIN
    (
        SELECT name, MIN(no) AS no
        FROM TABLE1
        GROUP BY name
    ) t2
    ON t1.name = t2.name AND t1.no = t2.no
) b ON a.name = b.name
SET a.address = b.address
like image 169
Tim Biegeleisen Avatar answered Jan 06 '26 08:01

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!