简体   繁体   中英

Insert one column from a table to another based on another column matching

I've been trying to get this query working but it's throwing an error:

UPDATE property_image PI
SET PI.property_id = (SELECT PTPI.property_id
                      FROM property_to_property_image PTPI
                      WHERE PI.id = PTPI.property_image_id)

It's saying:

Column 'property_id' cannot be null

But there are values in that column.

Use INNER JOIN clause :

UPDATE property_image PI
       INNER JOIN property_to_property_image PTPI
        ON PI.id = PTPI.property_image_id)
SET    PI.property_id;

This fails because there are entries in property_image that don't have an entry in property_to_property_image table and mysql tries to update property_id to null, which is not allowed for that column.

The question is, what do you want.

If you want to only update entries where you have an matching entry use inner join.

UPDATE property_image pi
INNER JOIN property_to_property_image ptpi ON pi.id = ptpi.property_image_id
SET pi.property_id = ptpi.property_id

Otherwise your query is fine, but needs a COALESCE(value, replacement) statement.

UPDATE property_image PI
SET PI.property_id = COALESCE(
    SELECT PTPI.property_id
    FROM property_to_property_image PTPI
    WHERE PI.id = PTPI.property_image_id), 0)

but is not very efficient, because it will make a new select for every row in property_image. Better: Modify the UPDATE query to use a left join

UPDATE property_image pi
LEFT JOIN property_to_property_image ptpi ON pi.id = ptpi.property_image_id
SET pi.property_id = COALESCE(ptpi.property_id, 0)

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