如何从一个表中选择一个值,并在另一个更新语句中使用该值。
但只使用一个sql语句?
有可能吗?
我有SQL
SELECT * FROM wp_posts WHERE post_name='hello-world';
并且存储的行用于:
UPDATE wp_postmeta SET meta_value='http://example.com' WHERE post_id={{here I need to put the value from the first statement liek first_table.ID or something}}
如何只在一个SQL语句中执行此操作?
有可能吗?
答案 0 :(得分:5)
UPDATE wp_postmeta
JOIN wp_posts
ON wp_postmeta.post_id = wp_posts.post_id
SET wp_postmeta.meta_value = 'http://example.com'
WHERE wp_posts.post_name = 'hello-world'
答案 1 :(得分:0)
IN
也适用
UPDATE wp_postmeta
SET meta_value = 'http://example.com'
WHERE post_id IN (SELECT id
FROM wp_posts
WHERE post_name = 'hello-world')
答案 2 :(得分:-1)
您可以使用加入或子查询。我以前更喜欢加入。
我会写这样的查询:
UPDATE wp_postmeta AS C1
LEFT OUTER JOIN wp_posts AS C2 ON C1.post_id = C2.post_id
SET meta_value='http://example.com'
WHERE C1.column_name = "search criteria";