php - 在 MySQL 中将 2 个更新查询作为一个运行

标签 php mysql sql

我有 2 个更新查询要合并为一个查询。有办法做到这一点吗?

查询 1:

update user_meta set
    meta_value = case meta_key
    when 'mobile' then '{$mobile}'
    when 'interest' then '{$interest}'
    when 'occupation' then '$occupation'
    when 'address' then '{$address}'
    when 'city' then '{$city}'
    when 'country' then '{$country}'
    when 'about' then '{$about}'
    when 'website' then '{$website}'
    else meta_value
    end
    where userid = {$id}

其他查询:

update user set fullname='{$fullname}' where userid={$id}

这两个查询是在同一个函数中同时执行的,但是有不同的表。另外,这样我必须运行两个更新查询。

如果我想将这个 when 语句放入循环中怎么办?如果要更新 100 个值,将非常困难。

最佳答案

可以在一条语句中更新多个表。

例如:

UPDATE user u
  JOIN user_meta m
    ON m.userid = u.userid
   SET m.meta_value = CASE m.meta_key
                      WHEN 'mobile'     THEN '{$mobile}'
                      WHEN 'interest'   THEN '{$interest}'
                      WHEN 'occupation' THEN '{$occupation}'
                      WHEN 'address'    THEN '{$address}'
                      WHEN 'city'       THEN '{$city}'
                      WHEN 'country'    THEN '{$country}'
                      WHEN 'about'      THEN '{$about}'
                      WHEN 'website'    THEN '{$website}'
                      ELSE m.meta_value
                      END
       , u.fullname = '{$fullname}'
   WHERE u.userid = {$id}

关于php - 在 MySQL 中将 2 个更新查询作为一个运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166967/

相关文章:

mysql - 我是否在我的 SQL 语句中运行了太多子查询?

sql - 2nf 第二范式困难练习

php - Unix `at` 命令通过 PHP

php - 如何从 php 中的 http 帖子接收文件(即文本文件)?

php - 一键删除mysql数据库记录

php - 使用 PHP 和 MySQL 创建基于标签的相关链接功能

sql - 从表中查找缺失值

PHP 重定向 - (SNI) 错误定向请求客户端需要一个新的连接 - 主机与服务器名称指示不匹配

c# - 在调用 Read() 之前访问字段的尝试无效。代码不工作

php - 使用 PHP 更新 mysql 中的 GRAVATAR