繁体   English   中英

标量子查询产生多个元素,使用 UNNEST

[英]Scalar subquery produced more than one element, using UNNEST

我有以下句子,正如我所读的,应该使用UNNEST ,但我不知道如何

select
(
  select 
    case 
      when lin = 4 then 1
      when lin != 4 then null
    end as FLAG,
  from table_1
  WHERE
    table_1.date = table_2.date
  AND
    table_1.acc = table_2.acc
) as FLAG
FROM
  table_2

我有很多子查询,这就是我不能使用 LEFT JOIN 的原因。 目前我的table_2有1300万条记录,table_1有4亿条记录,我想要的是能够为每个账户显示一个FLAG,知道数据宇宙是不同的。

我不能使用 LEFT JOIN ...
标量子查询产生了多个元素...

只需使用以下版本的查询 - 这在逻辑上等同于您的原始查询,但消除了您遇到的问题

select *, 
(
  select 1 as FLAG
  from table_1
  WHERE
    table_1.date = table_2.date
  AND
    table_1.acc = table_2.acc
  AND lin = 4
  LIMIT 1
) as FLAG
FROM
  table_2

这表明您希望从子查询中看到一个且只有一个值,但是当您加入table_1您会在dateacc字段上看到重复项。 如果您聚合值或从table_1中删除应该解决您的问题的重复项,那么为什么不使用更有效的JOIN呢?

-- This will solve your immediate problem, use any aggregation
-- technique, I picked MAX because why not. I do not know your use case.
select
(
  select 
    MAX(case 
      when lin = 4 then 1
      when lin != 4 then null
    end) as FLAG
  from table_1
  WHERE
    table_1.date = table_2.date
  AND
    table_1.acc = table_2.acc
) as FLAG
FROM
  table_2

一个更好的方法是

select
  case 
    when t1.lin = 4 then 1
    when t1.lin != 4 then null
  end as FLAG
FROM
  table_2 t2
LEFT JOIN
  table_1 t1 ON (
    t1.date = t2.date
    AND t1.acc = t2.acc
  )

正如您所说,左连接对您不起作用。 如果您希望多个结果嵌套在同一个子查询中,那么只需将您的子查询包装在ARRAY()函数中以允许重复值。

select
ARRAY(
  select 
    case 
      when lin = 4 then 1
      when lin != 4 then null
    end as FLAG
  from table_1
  WHERE
    table_1.date = table_2.date
  AND
    table_1.acc = table_2.acc
  
  -- Now you must filter out results that will return
  -- NULL because NULL is not allowed in an ARRAY
  AND
    table_1.lin = 4

) as FLAG
FROM
  table_2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM