SQL查询UPDATE由另一行过滤的两行

时间:2012-09-25 02:23:14

标签: mysql sql

我想要更新两行,列是meta_keymeta_valuemeta_key有两行我要过滤,它是first_namelast_name。我想更新meta_value,但会被first_namelast_name过滤。我的查询是这样的:

UPDATE 
  `wp_usermeta` 
SET 
  (`meta_value` = 'First Name' WHERE `meta_key` = 'first_name'), 
  (`meta_value` = 'Last Name' WHERE `meta_key` = 'last_name') 
WHERE `user_id` = (SELECT `user_id` FROM (SELECT MAX(`user_id`) AS `user_id`
FROM `wp_usermeta`) AS `reg`)

请帮助我..提前致谢!

2 个答案:

答案 0 :(得分:1)

您只需要一个级别的子选择。

UPDATE `wp_usermeta`
   SET `meta_value` = IF(`meta_key` = 'first_name', 'First Name',
                      IF(`meta_key` = 'last_name', 'Last Name',
                         `meta_value`))
 WHERE `user_id` = (SELECT MAX(`user_id`) FROM `wp_usermeta`)
   AND (`meta_key` = 'first_name' OR `meta_key` = 'last_name')

或者,您可以像大多数人一样使用两个单独的查询。

UPDATE `wp_usermeta`
   SET `meta_value` = 'First Name'
 WHERE `user_id` = (SELECT MAX(`user_id`) FROM `wp_usermeta`)
   AND `meta_key` = 'first_name';
UPDATE `wp_usermeta`
   SET `meta_value` = 'Last Name'
 WHERE `user_id` = (SELECT MAX(`user_id`) FROM `wp_usermeta`)
   AND `meta_key` = 'last_name';

答案 1 :(得分:1)

为什么不以这种方式更新

UPDATE `wp_usermeta` 
SET `meta_value` = 'First Name' 
WHERE `meta_key` = 'first_name' 
  AND `user_id` = (SELECT `user_id` FROM (SELECT MAX(`user_id`) AS `user_id` FROM `wp_usermeta`) AS `reg`)

UPDATE `wp_usermeta` 
SET `meta_value` = 'Last Name'
WHERE `meta_key` = 'last_name'
  AND `user_id` = (SELECT `user_id` FROM (SELECT MAX(`user_id`) AS `user_id` FROM `wp_usermeta`) AS `reg`)