2012-05-19 38 views
13

我正在尝试列出特定表的所有列,并确定每列是否未签名。如何确定列是否未签名?

在这里,我的测试夹具的例子:

CREATE TABLE ttypes 
(
    cbiginteger BIGINT UNSIGNED, 
    cinteger INT UNSIGNED, 
    csmallinteger SMALLINT UNSIGNED 
) ENGINE = InnoDB; 

为了列出特定表的所有列,我已经找到了两种可能性:

SHOW FULL COLUMNS 
FROM ttypes; 

按照documentation,这查询返回这些字段:字段,类型,空值,默认值,额外&评论。它们都不允许我确定列是否未签名。

之后,我看看information_schema.columns这是SHOW COLUMNS查询使用的基表。

SELECT ... 
FROM information_schema.columns 
WHERE table_name = 'ttypes'; 

不幸的是,没有一个结果字段允许我确定列是否是无符号的。

+0

? – Simon

回答

7

据我所知,这些属性的唯一存储位置是COLUMN_TYPE,INFORMATION_SCHEMA.COLUMNS

应包含在输出SHOW COLUMNS(内Type):

mysql> show columns from ttypes; 
+---------------+----------------------+------+-----+---------+-------+ 
| Field   | Type     | Null | Key | Default | Extra | 
+---------------+----------------------+------+-----+---------+-------+ 
| cbiginteger | bigint(20) unsigned | YES |  | NULL |  | 
| cinteger  | int(10) unsigned  | YES |  | NULL |  | 
| csmallinteger | smallint(5) unsigned | YES |  | NULL |  | 
+---------------+----------------------+------+-----+---------+-------+ 
3 rows in set (0.00 sec) 

不幸的是你必须解析出的内容Type,找到unsigned,或不unsigned在那里 - 它不”把任何东西放在签名列中。

+0

感谢您的快速回答。 – egeloen

4

要确定表中的所有变量类型,你可以运行这样的查询:像这样的查询

select COLUMN_NAME,COLUMN_TYPE from information_schema.COLUMNS where TABLE_NAME='ttypes' and COLUMN_TYPE LIKE '%unsigned%' 

这之后您可以轻松地确定类型特定的变量(例如cinterger) :

select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='ttypes' and COLUMN_TYPE LIKE '%unsigned%' and COLUMN_NAME LIKE 'cinteger' 

上面的代码将返回只有在未签名时才搜索的变量的名称。

最后,您可以使用mysql循环,过程或您最喜欢的脚本语言来使用此结果和/或继续搜索其他变量。

3

试试这个神奇:

select COLUMN_NAME, 
     COLUMN_TYPE, 
     IS_NULLABLE, 
     IF(COLUMN_TYPE LIKE '%unsigned', 'YES', 'NO') as IS_UNSIGNED 
     from information_schema.COLUMNS where TABLE_NAME='record1' 

输出

COLUMN_NAME COLUMN_TYPE  IS_NULLABLE IS_UNSIGNED 
----------- ---------------- ----------- ----------- 
id   int(10) unsigned NO   YES 
recordID  varchar(255)  YES   NO 
您正在使用什么版本的MySQL
相关问题