Select default value of column MySQL

ε祈祈猫儿з 提交于 2020-04-18 12:54:44

问题


I will not go deep in details. I have Java program which is creating tables in Database. The thing is that when table is created one of the fields get default value. So when I am adding elements to this field I want to select default value. Now loading of all element's ID is:

SELECT distinct(codeKind) FROM [table_name];

I want to be something like this:

SELECT [default value of column codeKind] from [table_name];

I checked many of answer of other similiar questions but none of them is OK.

Thanks.


回答1:


I also find solution:

select COLUMN_DEFAULT
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_SCHEMA='my_db' and TABLE_NAME='my_table' and COLUMN_NAME='my_column'



回答2:


Maybe this

drop table if exists t;
 create table t
 (id int auto_increment primary key,size int, sizecaption1 int default 10, sizecaption2 int, sizecaption3 int);

 insert into t (id,size) values 
 (1,22);
 insert into t values
 (2,22,22,22,22),
 (3,22,22,30,20),
 (4,22,1,2,3);

 select * from t where sizecaption1 = 
 (
 select column_default from information_schema.columns 
 where table_name = 't' and table_schema = 'sandbox' and column_default is not null
 ) ;

+----+------+--------------+--------------+--------------+
| id | size | sizecaption1 | sizecaption2 | sizecaption3 |
+----+------+--------------+--------------+--------------+
|  1 |   22 |           10 |         NULL |         NULL |
+----+------+--------------+--------------+--------------+
1 row in set (0.02 sec)



回答3:


use coalesce

select coalesce(codeKind,<def_value>)

Alternatively you can set a fixed value for table's creation DDL such as

create table my_table ( my_column default 0, col2 int .... ) , if you leave the column value as blank in the insert statement, then the value is automatically populated as zero.



来源:https://stackoverflow.com/questions/55534866/select-default-value-of-column-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!