【问题标题】:How to select and update records in one table by matching ids from it with another table?如何通过将一个表中的 id 与另一个表匹配来选择和更新一个表中的记录?
【发布时间】:2015-10-02 03:35:25
【问题描述】:

我正在使用 MySQL 和 phpMyAdmin

我是数据库、RDBMS、SQL 查询和所有这些东西的新手。

我有一个名为 user 的数据库表,其中包含以下字段:

user_id(primary key) Data type : int(10) 
user_group_id Data type : smallint(4)

我有另一个名为 user_field 的数据库表,其中包含以下字段:

user_id(primary key) Data type : int(10) 
country_child_id Data type : mediumint(8) 

现在我想为上面的表选择查询和更新查询。

在选择查询中,它应该返回表 user_field 的结果,其中 user_group_id = 6 and user.user_id = user_field.user_id

在更新查询中,我想从表user_field 更新country_child 字段(country_child = 1398),其中user_group_id = 6 and user.user_id = user_field.user_id

有人可以帮我构建查询吗?

谢谢。

【问题讨论】:

    标签: php mysql sql join


    【解决方案1】:

    尝试使用 INNER JOIN 获取要更新的记录。你可以试试这个查询:

    UPDATE a
    SET a.country_child_id = 1398
    FROM user_field AS a
    INNER JOIN user AS b ON a.user_id = b.user_id
    WHERE b.user_group_id = 6
    

    希望对你有帮助。

    编辑:

    对于 MySQL

    UPDATE user_field
    INNER JOIN user ON user.user_id = user_field.user_id
    SET user_field.country_child_id = 1398
    WHERE user.user_group_id = 6
    

    很抱歉,第一个更新语句只能在 MSSQL 中使用。 @Kendal 是对的,在 MySQL 的 SET 子句中,在 INNER JOIN 之后。

    【讨论】:

      【解决方案2】:

      我建议为此类更新使用where exists 子句,例如:http://sqlfiddle.com/#!9/0852a/1

      update user_field
      set country_child_id = 1398
      where exists (
        select * from user
        where user.user_id = user_field.user_id
        and user.user_group_id = 6
      )
      

      在示例小提琴中,您会注意到两条记录已更新——user_id = 2user_id = 6 都是 user_group_id = 6 的一部分。

      编辑:

      我应该提到我喜欢这种语法,因为我发现它易于阅读,尽管我可能还应该提到您可以使用更明确的inner join。请记住,mySQL 的语法似乎与其他语法略有不同,因为 join 子句位于 set 子句之前。

      至少,我是这样让它工作的:http://sqlfiddle.com/#!9/de73e/1

      update user_field
      inner join user
      on user.user_id = user_field.user_id
      set country_child_id = 1398
      where user.user_group_id = 6
      

      两个都试一下,让我知道哪个更快。干杯!

      【讨论】:

        猜你喜欢
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多