varchar列上的MySQL first_value返回错误格式的记录

时间:2019-06-03 04:22:43

标签: mysql sql window-functions

MySQL中的first_value函数以意外格式返回varchar列。

我有一个包含两列的表“ test”

create table test (col1 varchar(10), col2 integer);

并且有这样的记录

enter image description here

当我运行first_value函数时,我会得到这样的记录

select *, first_value(col1) over(partition by col1 order by col2 desc) as max_col1 
from test;

enter image description here

这是因为first_value仅适用于数字字段吗?

1 个答案:

答案 0 :(得分:2)

  

这是因为first_value仅适用于数字字段吗?

否,first_value()对于varchar数据类型也适用。
您得到的结果是正确的,但格式为十六进制
0x6B657931key1
0x6B657932key2
0x6B657933key3
因此,这可能是排序规则问题,也可能是您使用的软件出现问题。
如果您使用的是类似小提琴的网站,那么结果按原样出现并不奇怪。
无论如何,您可以在这里找到更多信息:https://dev.mysql.com/doc/refman/8.0/en/charset-syntax.html
如果问题仍然存在,则可以随时使用unhex()函数:

select unhex('6B657931')

将返回:

key1

或者:

select CAST(0x6B657931 AS CHAR)

还将返回:

key1

请参见demo