首页 > 解决方案 > 获取未设置 DEFAULT 值的数据库表列

问题描述

我们最近更新了我们的 mariadb 版本,它对默认列值更加严格,这意味着如果它们未设置且未在插入时定义,则不会插入新行。我正在寻找一种快速的方法来更新所有没有默认值的数据库列。

我想代码应该是这样的,记住这只是我想象的伪代码,运行它是行不通的:

$result = dbquery("SHOW TABLES");
   while ($row = dbarray($result))
   {
      foreach ($row as $key => $table)
      {
         // this is the query where it should check
         // if default value is set or not, but could not find information on how to do so
         $result2 = dbquery("SHOW COLUMNS FROM $table WHERE DEFAULT IS NOT SET");

         while ($column = dbarray($result2))
         {
           // SETTING A DEFAULT VALUE
           dbquery("ALTER $table ALTER $column SET DEFAULT NULL");
         }
      }
   }

注意:禁用严格模式不是我目前正在寻找的解决方案

关于如何选择未设置默认值的列的任何想法?

谢谢

标签: phpdatabasemariadb

解决方案


不为可空列提供值是可以的,所以我怀疑您想要识别没有默认值的不可空列。

您可以从以下位置获取该信息information_schema.columns

select table_name, column_name
from information_schema.columns
where column_default is null and isnullable = 'NO'

从那里开始,您需要决定应该使用哪个值作为默认值;答案取决于您的实际要求和列的数据类型。


推荐阅读