• 中文
    • English
  • 注册
  • 查看作者
  • 4-4:MySQL 单表更新记录UPDATE

    一.  更新记录 

    更新记录(单表更新)的语法结构:

    UPDATE [LOW_PRIORITY] [IGNORE] table_reference SET
    col_name1={expr1 | DEFAULT} [,col_name2={expr2 | DEFAULT}]...
    [WHERE where_condition]

    expr1 | DEFAULT 是指表达式或者默认值

    WHERE where_condition如果省略,则会更新所有记录:

    mysql> UPDATE users set age=age+5;
    Query OK, 8 rows affected (0.00 sec)
    Rows matched: 8  Changed: 8  Warnings: 0
    
    mysql> SELECT * FROM users;
    +----+----------+----------------------------------+-----+------+
    | id | username | password                         | age | sex  |
    +----+----------+----------------------------------+-----+------+
    |  1 | Tom      | 123                              |  30 |    1 |
    |  2 | John     | 123                              |  30 |    1 |
    |  3 | Tom      | 123                              |  30 |    1 |
    |  4 | John     | 123                              |  29 |    1 |
    |  5 | John     | 123                              |  15 |    1 |
    |  6 | Tom      | 123                              |  30 |    1 |
    |  7 | Rose     | 202cb962ac59075b964b07152d234b70 |  15 |    0 |
    |  8 | BEn      | 456                              |  15 | NULL |
    +----+----------+----------------------------------+-----+------+
    8 rows in set (0.00 sec)

    可以看到,8行受到影响,所有的age都在原先的基础上加了5。

    二.    根据特定的条件更新记录

    比如给所有偶数id用户年龄加10岁:

    mysql> UPDATE users SET age = age + 10 WHERE id % 2 = 0;
    Query OK, 4 rows affected (0.00 sec)
    Rows matched: 4  Changed: 4  Warnings: 0
    
    mysql> SELECT * FROM users;
    +----+----------+----------------------------------+-----+------+
    | id | username | password                         | age | sex  |
    +----+----------+----------------------------------+-----+------+
    |  1 | Tom      | 123                              |  29 |    0 |
    |  2 | John     | 123                              |  38 |    0 |
    |  3 | Tom      | 123                              |  27 |    0 |
    |  4 | John     | 123                              |  35 |    0 |
    |  5 | John     | 123                              |  10 |    0 |
    |  6 | Tom      | 123                              |  34 |    0 |
    |  7 | Rose     | 202cb962ac59075b964b07152d234b70 |   8 |    0 |
    |  8 | BEn      | 456                              |  17 |    0 |
    +----+----------+----------------------------------+-----+------+
    8 rows in set (0.00 sec)

    可以看到id为2,4,6,8的记录被修改

  • 0
  • 0
  • 0
  • 3.1k
  • 请登录之后再进行评论

    登录

    赞助本站

    • 支付宝
    • 微信
    • QQ

    感谢一直支持本站的所有人!

    单栏布局 侧栏位置: