【问题标题】:add Exists operator in a union sql query在联合 sql 查询中添加 Exists 运算符
【发布时间】:2021-02-18 23:39:29
【问题描述】:

我有两个表使用联合来组合它们的结果集我的问题是 UNION 中的每个 SELECT 语句必须具有相同数量的列和数据类型,我没有相同数量的列所以正在创建空列

select
d.deal_id as order_id,
EXISTS(select * from table1 c where d.user_id = c.user_id) as IsUser, --this returns boolean value
from table 1 c
union
select
cast(o.id as varchar) as order_id,
coalesce('No_user'::text,'0'::text) as IsUser, --i get an error :UNION types boolean and character varying cannot be matched
from table2 o

如何在 table2 中创建一个与 table1 的布尔数据类型匹配的空列

【问题讨论】:

  • 你能提供表格内容和你的设计者输出吗?

标签: postgresql union exists sqldatatypes


【解决方案1】:

如何在 table2 中创建一个与 table1 的布尔数据类型匹配的空列

通过将 NULL 放入第二个查询的 SELECT 列表中。

通常(在 SQL 中)列的数据类型由联合集中的第一个查询决定,其他查询必须匹配。后续查询也不需要列别名,但它们可能有助于使查询更具可读性:

select
  d.deal_id as order_id,
  EXISTS(select * from table1 c where d.user_id = c.user_id) as IsUser, --this returns boolean value
from table 1 c
union
select
  cast(o.id as varchar) as order_id,
  null --IsUser
from table2 o

如果您遇到第一个查询中列的类型与输出中您想要的不同的情况,则转换第一列:

select 1::boolean as boolcol
UNION
select true

这将确保该列是布尔值,而不是给出“整数和布尔值不能匹配”。还请记住,如果您需要,可以将 NULL 强制转换为类型,例如select null::boolean as bolcol

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多