在MySQL 5.6.23上创建的简单测试表:
CREATE TABLE `test` (
`tinyint` tinyint(1) NOT NULL DEFAULT 0,
`int` int(11) NOT NULL DEFAULT 0
);
请注意DEFAULT
值的写法:字面0
。一旦创建,我就会:
SHOW CREATE TABLE `test`;
并获得:
CREATE TABLE `test` (
`tinyint` tinyint(1) NOT NULL DEFAULT '0',
`int` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1
DEFAULT
值已获得报价:'0'
!
为什么会这样?更重要的是,我原本应该用引号围绕数字默认值吗?
答案 0 :(得分:6)
当然,SHOW CREATE TABLE
无法检索原始CREATE TABLE
代码。即使它实际上存储在某个地方,它也不一定反映当前的表定义(您可以随后ALTER TABLE
尽可能多地使用它。该代码需要根据需要重新创建。 MySQL服务器主要用C语言编写,带有一些C ++。我无法确切地告诉它(我只是猜测,因为我知道很少有C而且我对MySQL代码库不熟悉),但这样做的功能可能是this:
int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet,
HA_CREATE_INFO *create_info_arg, bool show_database)
...调用this other one:
static bool print_default_clause(THD *thd, Field *field, String *def_value,
bool quoted)
如果你查看源代码,你会意识到它是一个冗长乏味的字符串连接,跨越数百行。 (C是闪电般快速,因为它比现代高级语言更接近机器,但这样做的代价是不太适合快速开发。)
没有必要引用一个数字。但是多年前编写这个代码生成器的人并不关心这个细节。 MySQL会在需要时自动将字符串转换为数字,结果会更好或更差:
mysql> SELECT 1+99, '1'+99, '1x' + '99x', '1' + 'x99';
+------+--------+--------------+-------------+
| 1+99 | '1'+99 | '1x' + '99x' | '1' + 'x99' |
+------+--------+--------------+-------------+
| 100 | 100 | 100 | 1 |
+------+--------+--------------+-------------+
1 row in set, 3 warnings (0.00 sec)
mysql> SHOW WARNINGS;
+---------+------+-----------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '99x' |
| Warning | 1292 | Truncated incorrect DOUBLE value: '1x' |
| Warning | 1292 | Truncated incorrect DOUBLE value: 'x99' |
+---------+------+-----------------------------------------+
3 rows in set (0.00 sec)
由于引用的数字来自实际列的实际默认值,因此它永远不会是无效的数字(否则您无法创建表)。所以这不是什么大不了的事。
总结一下:该代码只是某人多年前写过的模板,并不是风格指南或编码标准。
答案 1 :(得分:1)
这可能只是SHOW CREATE TABLE语法使用它的方式。我能够使用这两种方法提交它,它对我有用。
<body ng-app="testApp">
<h1>Users table </h1>
<table class="table table-striped" ng-controller="TestController as test">
<p> Sorting predicate {{predicate}}; reverse = {{reverse}} </p>
<thead>
<tr>
<th>#</th>
<th>
Username
</th>
...
</tr>
</thead>
<tbody>
<tr ng-repeat="datafinal in test.rezdata" >
<td>{{ datafinal.id}} </td>
<td>{{datafinal.username}} </td>
...
</tr>
</tbody>
</table>
</body>