UPDATE on SELECT With MySQL

Previously if there a need to something like this, I would have definitely create a temporary tool using PHP to automatically loop a SELECT and UPDATE each field inside the loop, for example:

$sql = "SELECT * FROM item";
$query = $this->db->query($sql);
foreach( $query->result_array() as $row ) :
    $this->db->query("UPDATE relationship
        SET rel_date=?
        WHERE (rel_value=? AND rel_type=1)", array(
        $row['item_datetime'],
        $row['item_id']
    ));
endforeach;

This actually can be simplify using only MySQL query such as:

UPDATE relationship r, item i
    SET r.rel_date=i.item_datetime
    WHERE (r.rel_value=i.item_id AND r.rel_type=1)
Posted in Code Snippet, MySQL | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>