7

MySQL 数据库操作笔记若干

 3 years ago
source link: https://yihui.org/cn/2009/05/mysql-database-manipulation-notes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

MySQL 数据库操作笔记若干

谢益辉 / 2009-05-22


学习最好的方法莫过于实践,最快的途径莫过于示例,这段时间网站搬家,迫使我不断去看一些 SQL 操作方法,最终记载于此,以便将来参考。

1、时间操作

例:将 GMT 时间更改为 GMT+8,可用 INTERVAL 把一段时间加到一个字段上。

UPDATE `wpcn_posts` SET `post_date` = `post_date_gmt` + INTERVAL 8 HOUR
  WHERE `post_date_gmt` = `post_date`

本例是为了对付 Bo-Blog 搬家到 WP 时大部分时间记录都没有被正确转换到 GMT+8 时区的问题。

2、字符查找替换

例:将某个图片的错误文件名更改为正确文件名。

UPDATE `wpcn_comments` SET `comment_content` = REPLACE (
`comment_content`,
'emot/ok',
'emot/pig'
)
WHERE `comment_content` LIKE '%emot/ok%'

本例是为了对付 Bo-Blog 的 pig.gif 图片文件名被错误替换为 ok.gif 的问题,用到了 REPLACE 函数和 LIKE 操作符,注意 LIKE 后面的字段用 %% 匹配,而非 *

3、用 R 帮忙

例:批量更新日志的永久链接。

cat(sprintf("UPDATE `wpen_posts` SET post_name = '%s' WHERE ID =%d;",
    x[, 3], x[, 1]), sep = "\n")

由于我不知道 SQL 里面如何用数组或向量,因此在批量处理的时候就用笨办法执行了,即:写 n 条 SQL 语句一起执行。R 一向都是向量化操作,因此只需要把日志的 ID 和 post_name 准备好,然后用一个 sprintf() 就生成所有的 SQL 语句了,扔到 phpMyAdmin 中执行一下,所有的日志链接就更新了,省得把每一篇日志打开依次修改。

以上 R 语句生成如下结果:

UPDATE `wpen_posts` SET post_name = 'tidy-up-your-r-code' WHERE ID =1;
UPDATE `wpen_posts` SET post_name = 'dare-be-defeated' WHERE ID =2;
....

插一句,对于英文日志,永久链接就是把空格替换为 -,用正则表达式删掉不是 [:alnum:] 的字符即可。

4、用 mysqldump 备份数据库

这个命令可以以多种形式备份 MySQL 数据库,这里举例将数据库备份为 *.sql 的 SQL 语句脚本:

mysqldump -u db_user -p -r result_filename.sql database_name

由于 mysqldump 命令是独立的程序,所以不要先登录进 mysql 界面,直接在终端或 command 窗口运行即可。这样的备份文件可以在将来在 mysql 中用 source 命令导入:

source result_filename.sql

这样看来备份数据库也是很容易的事情,不过导入导出的时候可能会遇到编码问题。

拿小概率事件说事:中央关键词对年轻人的七项忠告 PHP 的 301 重定向(从 Bo-Blog 搬家到 Wordpress 的后续工作)

Disqus Utterances Preferences

© Yihui Xie 2005 - 2020

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK