首页 > 解决方案 > 在 mysql 查询中键入自省

问题描述

是否有一个函数mysql可以告诉查询中评估的表达式/列/文字是什么类型?我不是指信息模式,而是类似:

SELECT
    TYPE('Washington') as literal_type,
    TYPE(IF(col='a', col, 2)) as expression_type,
    TYPE(col) as col_type
FROM table

我会得到类似的东西:

VARCHAR      --      INT64          --      DATE

这主要用于调试目的。

标签: mysqlsql

解决方案


不,您所描述的内容没有功能。

与您所说的最接近的事情是使用带有--column-type-info显示结果集元数据选项的 MySQL 客户端。

但是,如果您以编程方式使用 SQL,那将无济于事。

mysql> select 'Washington' as literal_type, if(d = 9, d, 2) as expression_type, t as col_type from mytable;

输出:

Field   1:  `literal_type`
Catalog:    `def`
Database:   ``
Table:      ``
Org_table:  ``
Type:       VAR_STRING
Collation:  utf8mb4_0900_ai_ci (255)
Length:     40
Max_length: 10
Decimals:   31
Flags:      NOT_NULL 

Field   2:  `expression_type`
Catalog:    `def`
Database:   ``
Table:      ``
Org_table:  ``
Type:       LONGLONG
Collation:  binary (63)
Length:     20
Max_length: 1
Decimals:   0
Flags:      BINARY NUM 

Field   3:  `col_type`
Catalog:    `def`
Database:   `test`
Table:      `mytable`
Org_table:  `mytable`
Type:       DATE
Collation:  binary (63)
Length:     10
Max_length: 10
Decimals:   0
Flags:      BINARY 


+--------------+-----------------+------------+
| literal_type | expression_type | col_type   |
+--------------+-----------------+------------+
| Washington   |               2 | 2020-11-21 |
+--------------+-----------------+------------+
1 row in set (0.00 sec)

推荐阅读