You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何筛选information_schema.columns视图返回的列及改写插入语句获取可空列

嘿,我来帮你搞定这两个PostgreSQL的问题:

问题1:如何筛选通过information_schema.columns视图获取到的列?

information_schema.columns是PostgreSQL里用来查看数据库列元数据的常用视图,它包含了大量字段(比如table_name、column_name、is_nullable、data_type、table_schema等)。要筛选这个视图的结果,只需要通过WHERE子句添加对应的过滤条件即可,给你几个常用场景的例子:

  • 筛选指定表(比如名为users的表)的所有列:
    SELECT * FROM information_schema.columns WHERE table_name = 'users';
    
  • 筛选public模式下,所有表中数据类型为文本类的列:
    SELECT column_name, table_name 
    FROM information_schema.columns 
    WHERE table_schema = 'public' 
      AND data_type IN ('character varying', 'text');
    
  • 筛选指定表中不允许为空的列:
    SELECT column_name 
    FROM information_schema.columns 
    WHERE table_name = 'users' 
      AND is_nullable = 'NO';
    

简单来说,你需要什么筛选规则,就把对应的字段和条件加到WHERE里就行。

问题2:修改INSERT语句,仅获取允许设置为NULL的列

你只需要在原SQL的WHERE子句里加上is_nullable = 'YES'这个条件就行,因为information_schema.columns里的is_nullable字段值为YES时,表示该列允许存储NULL值。修改后的完整语句如下:

INSERT INTO colonnes ("colonnesName") 
SELECT "column_name" 
FROM information_schema.columns 
WHERE "table_name" = tableName 
  AND "is_nullable" = 'YES';

这样就能确保只有允许为空的列名被插入到colonnes表中啦。

内容的提问来源于stack exchange,提问作者Mathieu Arthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:39:10