SQL: join two tables (LEFT OUTER JOIN) then update values

前提是你 提交于 2021-01-27 18:33:55

问题


Im trying to update a value in one column based on a value in another table.

I can do this if the columns are all in the same table like this:

UPDATE wp_posts 
SET post_date = REPLACE (post_date, 'X', 'Y') 
WHERE meta_value = 'Z';

But I need to join two tables first before I can update:

SELECT * 
FROM wp_posts 
LEFT OUTER JOIN wp_postmeta ON post_id = post_id

How can I update based on the two tables I have joined?


回答1:


Try this way, if you use SQL Server

UPDATE WP
SET WP.post_date = REPLACE(WPM.post_date, 'X', 'Y') 
FROM wp_posts WP 
   LEFT OUTER JOIN wp_postmeta WPM ON WP.post_id = WPM.post_id
WHERE WP.meta_value = 'Z';

UPDATE:

If you're using MySQL. Here's Update for MySQL

UPDATE wp_posts WP 
   LEFT JOIN wp_postmeta WPM ON WP.post_id = WPM.post_id
SET WP.post_date = REPLACE(WPM.post_date, 'X', 'Y') 
WHERE meta_value = 'Z';



回答2:


SQL Server

UPDATE wp_posts 
post_date = REPLACE (post_date, 'X', 'Y')
FROM wp_posts WP LEFT OUTER JOIN wp_postmeta WPM ON WP.post_id = WPM.post_id
WHERE meta_value = 'Z';

MySQL

UPDATE wp_posts 
LEFT JOIN wp_postmeta WPM ON WP.post_id = WPM.post_id 
SET post_date = REPLACE (post_date, 'X', 'Y')
WHERE meta_value = 'Z'



回答3:


 UPDATE wp_posts SET post_date = REPLACE (WPM.post_date, 'X', 'Y')
 FROM wp_posts AS WP
 LEFT OUTER JOIN wp_postmeta AS WPM ON WP.post_id = WPM.post_id
 WHERE WP.meta_value = 'Z'


来源:https://stackoverflow.com/questions/12109760/sql-join-two-tables-left-outer-join-then-update-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!