对我来说似乎是个错误,我可以通过以下方式确认这种令人困惑的行为:
10.2.14-MariaDB
如果可能,可以将整数值转换为双精度值:
SELECT cast(20 as double) UNION SELECT null UNION SELECT 2.2;
或确保您首先拥有double值:
SELECT 2.2 UNION SELECT null UNION SELECT 22;
阅读@Evan Carroll答案中的评论后的进一步观察
select 20 union select null union select 2;
+------+
| 20 |
+------+
| 20 |
| NULL |
| 2 |
+------+
好的,使用int值似乎不会产生错误。
select 20 union select null union select 9.0;
+------+
| 20 |
+------+
| 9.9 |
| NULL |
| 9.0 |
+------+
错误:好像输出是十进制(2,1)
create table tmp as select * from (select 20 as x
union
select null
union
select 9.0) as t
describe tmp;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| x | decimal(2,1) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
该错误未隔离到命令行界面,对于python2-mysql-1.3.12-1.fc27.x86_64也存在:
>>> import MySQLdb
>>> db = MySQLdb.connect(host="localhost", user="*****", passwd="*****", db="test")
>>> cur = db.cursor()
>>> cur.execute("SELECT 20 union select null union select 2.2")
3L
>>> for row in cur.fetchall() :
... print row
...
(Decimal('9.9'),)
(None,)
(Decimal('2.2'),)
奇怪的是,如果首先移动null或最后移动null,该错误就会消失:
select null union select 20 union select 9.0;
select 20 union select 9.0 union select null;
+------+
| NULL |
+------+
| NULL |
| 20.0 |
| 9.0 |
+------+
如果将null放在首位,则结果类型为小数(20,1)。如果放置null,则最后一个结果类型为小数(3,1)
如果将另一条腿添加到联合中,该错误也将消失:
select 20 union select 6 union select null union select 9.0;
+------+
| 20 |
+------+
| 20.0 |
| 6.0 |
| NULL |
| 9.0 |
+------+
结果类型十进制(20,1)
在中间添加另一个null可以保留错误:
select 20 union select null union select null union select 9.0;
+------+
| 20 |
+------+
| 9.9 |
| NULL |
| 9.0 |
+------+
但是在开头添加null可以解决此问题:
select null union select 20 union select null union select null union select 9.0;
+------+
| NULL |
+------+
| NULL |
| 20.0 |
| 9.0 |
+------+
如预期的那样,将第一个值强制转换为十进制(3,1)。
最后,显式转换为十进制(2,1)会产生相同的错误,但带有警告:
select cast(20 as decimal(2,1));
+--------------------------+
| cast(20 as decimal(2,1)) |
+--------------------------+
| 9.9 |
+--------------------------+
1 row in set, 1 warning (0.00 sec)