2015-08-24 28 views
0

如何通过数据库中的MySQL查询更改嵌入帖子中的链接结构? 例如,我想改变的链接结构是这样的:(第一行第二)如何使用查询更改数据库中的链接结构

http://forum.site.com/thread1001.html 
http://forum.site.com/index.php?app=forums&module=forums&controller=topic&id=1001 

这可能吗?如果不是,还有其他方法吗? 谢谢...

回答

1

你正在寻找在MySQL中的一些字符串操作,是吗?

https://dev.mysql.com/doc/refman/5.6/en/string-functions.html

SELECT 
    CONCAT(
    SUBSTRING_INDEX(url_field, "/", 3), 
    "/index.php?app=forums&module=forums&controller=topic&id=", 
    SUBSTRING(
     SUBSTRING_INDEX(
     SUBSTRING_INDEX(url_field, "/", -1), 
     ".", 
     1 
    ), 
     7 
    ) 
) 
; 

为了使这是一个UPDATE声明:

UPDATE table_name 
SET url_field = 
    CONCAT(
    SUBSTRING_INDEX(url_field, "/", 3), 
    "/index.php?app=forums&module=forums&controller=topic&id=", 
    SUBSTRING(
     SUBSTRING_INDEX(
     SUBSTRING_INDEX(url_field, "/", -1), 
     ".", 
     1 
    ), 
     7 
    ) 
) 
; 

如果你有这个URL嵌入TEXT或东西(比如用户评论),里面那么你就必须做更多的工作来从中提取URL:

SELECT 
    CONCAT(
    SUBSTRING_INDEX(@url_field, "http://", 1), 
    "http://", 
    SUBSTRING_INDEX(SUBSTRING_INDEX(@url_field, "http://", -1), "/", 1), 
    "/index.php?app=forums&module=forums&controller=topic&id=", 
    SUBSTRING(
     SUBSTRING_INDEX(
     SUBSTRING_INDEX(@url_field, "/", -1), 
     ".", 
     1 
    ), 
     7 
    ), 
    SUBSTRING_INDEX(SUBSTRING_INDEX(@url_field, "http://", -1), ".html", -1) 
) 
; 

还是要UPDATE:在SQL

UPDATE table_name 
SET text_field = 
    CONCAT(
    SUBSTRING_INDEX(text_field, "http://", 1), 
    "http://", 
    SUBSTRING_INDEX(SUBSTRING_INDEX(text_field, "http://", -1), "/", 1), 
    "/index.php?app=forums&module=forums&controller=topic&id=", 
    SUBSTRING(
     SUBSTRING_INDEX(
     SUBSTRING_INDEX(text_field, "/", -1), 
     ".", 
     1 
    ), 
     7 
    ), 
    SUBSTRING_INDEX(SUBSTRING_INDEX(text_field, "http://", -1), ".html", -1) 
) 
; 

逐步复只有我害怕。 (您可以优化上述内容。)

为了将更改的记录数量降到最低 - 确保最后有一个好的WHERE子句。


说明:

SET @url_field := "abcdedef http://forum.site.com/thread1001.html xyz"; 
SELECT 
    -- CONCAT(
    SUBSTRING_INDEX(@url_field, "http://", 1), -- Everything left of URL 
    "http://", -- Restore the http:// lost in the substring above 
    SUBSTRING_INDEX(SUBSTRING_INDEX(@url_field, "http://", -1), "/", 1), -- Get the website domain name 
    "/index.php?app=forums&module=forums&controller=topic&id=", -- Append the parts of our new URL we know won't change 
    SUBSTRING(
     SUBSTRING_INDEX(
     SUBSTRING_INDEX(@url_field, "/", -1), -- Get the ID from the original URL - starting at final/
     ".", -- ... stopping at .html 
     1 
    ), 
     7 -- ... dropping the word "thread" from the start 
    ), 
    SUBSTRING_INDEX(SUBSTRING_INDEX(@url_field, "http://", -1), ".html", -1) -- capture everything after the URL 
    --) 
; 

注意这可能会破坏其他网址。不幸的是,在MySQL中,我们没有插件/扩展的正则表达式替换等(据我所知)。

+0

感谢您的回复!但不适用于SELECT,我正在寻找REPLACE。 – HoomanMns

+0

没问题,您可以将其更改为更新...我将修改我的答案。 – wally

+0

已更新的答案。 – wally