Skip to content

Instantly share code, notes, and snippets.

@lewangdev
Last active July 8, 2022 10:08
Show Gist options
  • Save lewangdev/a5e4ead0622de0ab1fb97d98446aff0e to your computer and use it in GitHub Desktop.
Save lewangdev/a5e4ead0622de0ab1fb97d98446aff0e to your computer and use it in GitHub Desktop.
Pattern of writing UPDATE query based on SELECT Query

Pattern:

UPDATE
    `table1` AS `dest`,
    (
        SELECT
            *
        FROM
            `table2`
        WHERE
            `id` = x
    ) AS `src`
SET
    `dest`.`col1` = `src`.`col1`
WHERE
    `dest`.`id` = x
;

Instance:

UPDATE 
	yl_inpatient_vital_sign AS dest,
	(
	 	SELECT 
			id,inpatient_no 
	 	FROM 
			yl_inpatient
	 ) AS src
SET 
	dest.inpatient_id = src.id 
WHERE 
	dest.`inpatient_no` = src.inpatient_no
;

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment