Mysql如何将数据从一个字段复制到同一个表中的其他字段

时间:2013-03-06 06:50:25

标签: php mysql sql phpmyadmin sql-update

我有mysql表如下:

    id      host             url
--------------------------------------
    1                   test.com/index.php
    2                   domain.com/list
    3                   www.stackoverflow.com/questions/ask

我需要输出如下

    id      host                 url
------------------------------------------
    1     test.com             test.com/index.php
    2     domain.com           domain.com/list
    3     stackoverflow.com    www.stackoverflow.com/questions/ask

提前致谢。

3 个答案:

答案 0 :(得分:4)

使用SUBSTRING_INDEX(str, delim, count)

UPDATE tablename
SET host = SUBSTRING_INDEX(url, '/', 1);

SQL Fiddle Demo

这会使你的表看起来像:

| ID |                  HOST |                                 URL |
--------------------------------------------------------------------
|  1 |              test.com |                  test.com/index.php |
|  2 |            domain.com |                     domain.com/list |
|  3 | www.stackoverflow.com | www.stackoverflow.com/questions/ask |

答案 1 :(得分:2)

假设您的表名为t

UPDATE t
SET host=SUBSTRING_INDEX(url, '/', 1);

答案 2 :(得分:0)

使用SUBSTRING_INDEX

UPDATE tbl1 SET host = SUBSTRING_INDEX(url, '/', 1)