postgresql - 到目前为止,如何在 union 中转换空列?

标签 postgresql

[SQL 初学者]

我有这样的 sql 查询:

select * from 
(select '' as dates from table1

union 

select dates from table2)

当我运行此查询时出现错误 UNION types text and timestamp without time zone cannot be matched

我试图将表 2 中的 dates 列转换为 varchar,但这不是我想要的。如何将 table1 中的空字段转换为日期时间?

我试过这个:

select * from 
(select cast(('' as dates) as date) as dates from table1

union 

select dates from table2)

但这也不起作用。

最佳答案

给它 null 值。这可以转换为任何数据类型。

SELECT * 
FROM (
    SELECT null::timestamp AS dates FROM table1
    UNION
    SELECT dates FROM table2
) t

注意:您还可以使用 VALUES,而不是“空”日期的 SELECT

关于postgresql - 到目前为止,如何在 union 中转换空列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898274/

相关文章:

python - 如何解决由于 Calendar API 升级导致创建的事件时间不匹配?

ruby-on-rails - 使用带有事件记录的连接表时如何连接模型的多个实例?

ruby - 重构以减少重复

postgresql - 无法混合 ecto.create。多个错误

postgresql - 如何将 docker 容器添加到现有的 docker 网络

postgresql - Postgres 批量收集和 Forall 删除

postgresql - 我可以在 PostgreSQL 9.3 中将 TRUNCATE + COPY + ANALYZE 替换为 TRUNCATE + COPY/FREEZE 吗

ruby-on-rails - 使用 Active Record 检索具有唯一字段的记录

python - 从 psycopg2 中的模式获取数据

mysql - 处理 10K 插入和频繁选择操作的数据库服务器设置