MySQL:不同的评估命令行和mysql控制台

时间:2014-03-12 04:53:16

标签: mysql sql command-line

我很惊讶mysql在运行mysql -e "$query"并输入查询时使用mysql在mysql控制台中评估同一语句的命令行。 我有一个带有时间戳字段create_date的表。我以不同的方式运行相同的命令并获得不同的结果:

在mysql控制台中:

$ mysql -uuser -ppassword database1
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 33608
Server version: 5.5.32-31.0 Percona Server (GPL), Release rel31.0, Revision 549

Copyright (c) 2009-2013 Percona Ireland Ltd.
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select DATE_ADD(create_time, INTERVAL DATEDIFF('2014-03-13', "2013-03-13") DAY) as date from table1;
+---------------------+
| date                |
+---------------------+
| 2014-03-08 00:00:11 |
| 2014-03-08 00:00:22 |
| 2014-03-10 00:00:33 |
| 2014-03-10 00:00:44 |
| 2014-03-12 00:00:55 |
| 2014-03-12 00:00:32 |
| 2014-03-08 00:00:42 |
| 2014-03-08 00:00:23 |
+---------------------+
8 rows in set (0.00 sec)

使用-e参数从命令行执行的相同查询会产生空结果:

$ mysql -uuser -ppassword urbanout_www -e 'select DATE_ADD(create_time, INTERVAL DATEDIFF('2014-03-13', "2013-03-13") DAY) as date from table1;'
+------+
| date |
+------+
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
| NULL |
+------+

对此有何解释?

1 个答案:

答案 0 :(得分:1)

当你在查询中使用单引号时,它们会终止shell的引用,而不是发送给MySQL。尝试:

$ mysql -uuser -ppassword urbanout_www -e 'select DATE_ADD(create_time, INTERVAL DATEDIFF("2014-03-13", "2013-03-13") DAY) as date from table1;'