如果我想要一个字符串并创建一个表(这在strict mode中失败),
CREATE TABLE g
AS SELECT CAST('2147483699' AS int);
我如何告诉它我想要一个bigint类型?我也会得到一个int(10)类型.选择它也很幽默,
+---------------------------+
| CAST('2147483699' AS int) |
+---------------------------+
| 2147483647 |
+---------------------------+
数据实际上是错误的,它默默地失败了. I know that’s a known issue with this database having really poor defaults,但我怎么能把这张桌子作为bigint创建呢?
CREATE TABLE g
AS SELECT CAST('2147483699' AS bigint);
这样做我得到这个错误,
ERROR 1064 (42000): You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near ‘bigint)’ at line 2
如何将一个整数投入bigint?
Postgresql的
使用Postgresql,它非常简单.除了在转换为int时抛出异常,还可以使用强制转换为bigint
SELECT CAST('2147483699' AS bigint);
int8
------------
2147483699
解决方法:
CREATE TABLE g
AS SELECT CAST('2147483699' AS int);
MariaDB 10.1.32,默认sql_mode(非严格)
Query OK, 1 row affected, 1 warning (0.19 sec) Records: 1 Duplicates:
0 Warnings: 1
警告是:
| Warning | 1264 | Out of range value for column ‘CAST(‘2147483699′ AS int)’ at row 1 |
是的,从表格中选择是有趣的,但鉴于警告,这并不奇怪.
(我目前没有MariaDB 10.2实例,但是对dbfiddle.uk进行测试表明它也失败了,尽管再次没有静默.)
没有警告.
select * from g;
得到:
+---------------------------+
| CAST('2147483699' AS int) |
+---------------------------+
| 2147483699 |
+---------------------------+
1 row in set (0.000 sec)
并且该列确实被创建为bigint(10).
ERROR 1064 (42000): You have an error in your sql Syntax; check the manual that corresponds to your MysqL server version for the right Syntax to use near ‘int)’ at line 2
电脑说没有.
结论
MariaDB或MysqL可以作为bigint投射吗?正如我们所看到的,是的,MariaDB 10.3可以(虽然它还不是GA ……但现在肯定会是任何一天).但是,它只能隐式地转换为bigint.您不能显式地转换为bigint,就像您不能转换为varchar(但请参阅MDEV-11283),text,float,tinyint等.您可以强制转换为有限数量的数据类型.这没有很好的文档记录,但CAST似乎只支持与CONVERT function列出的相同数据类型.