提问人:dda 提问时间:9/28/2023 最后编辑:dda 更新时间:9/28/2023 访问量:43
为什么 coalesce 返回标量子查询返回了多行,即使值不同 - SQL
why coalesce returns Scalar sub-query has returned multiple rows even though the values are distinct - SQL
问:
我有 2 个表要加入。这些表是 和kp.pi
g.gu
kp.pi
与 based on 和 on 连接,我想在此连接后从表中获取字段。g.gu
pi.xx_id = gu.yy_id
pi.xx_type = gu.yy_type
userid
g.gu
但是,在某些情况下,由于类型(即 pi.xx_type = gu.yy_type)在两个表中不匹配,因此它将返回 null for 。因此,如果类型不匹配,我想排除此连接条件以获取 from。userid
userid
g.gu
所以查询是一样的,只是排除了从中获取用户ID的连接条件。pi.xx_type = gu.yy_type
g.gu
我尝试使用合并来执行此操作,但不知何故不断收到错误:
Scalar sub-query has returned multiple rows
即使表中的值不同。userid
g.gu
谁能看看我下面的查询有什么问题?
select submission_id, xx_id, coalesce (userid ,
(select distinct userid from
( SELECT *
from kp.pi
where source like '%abc%'
and id in (123,
456,
7877
)
) pi
left join
(select yy_id,
id as userid,
case
when type = 1 then 'bb'
when type = 2 then 'cc'
when type = 3 then 'dd' end as yy_type
from g.gu)
on xx_id = yy_id
)
)
as test_userid
from
(select
id as submission_id,
xx_id,
xx_type
from kp.pi
where source like '%abc%'
and id in (123,
456,
7877
)
) pi
left join
(select yy_id,
id as userid,
case
when type = 1 then 'bb'
when type = 2 then 'cc'
when type = 3 then 'dd' end as yy_type
from g.gu
) gu
on pi.xx_id = gu.yy_id
and pi.xx_type = gu.yy_type
答:
如果没有代表性数据的样本,则需要对数据进行假设。我相信您正在尝试优先考虑具有匹配的用户 ID,但如果无法使用,请在不满足该条件的情况下使用 userid。与其尝试将此逻辑放入连接中,我建议使用它将为每个行号提供 1,并且由于使用的顺序,该行号将属于类型 1,2,3(如果可用),否则可用于下一个可用类型。然后,通过在联接条件中使用此行号,您只能获得 1 行,并且该行将按匹配类型/不匹配类型进行优先级排序。pi.xx_type = gu.yy_type
row_number() over(partition by id order by case when type in (1,2,3) then 1 else 2 end)
gu.id
gu.id
SELECT
pi.id AS submission_id
, pi.xx_id
, gu.userid AS test_userid
FROM kp.pi
LEFT JOIN (
SELECT
yy_id
, id AS userid
, CASE
WHEN type = 1 THEN 'bb'
WHEN type = 2 THEN 'cc'
WHEN type = 3 THEN 'dd'
END AS yy_type
, row_number() over(partition by id
order by case when type in (1,2,3) then 1 else 2 end) as rn
FROM g.gu
) gu ON pi.xx_id = gu.yy_id AND gu.rn = 1
WHERE pi.source LIKE '%abc%'
AND pi.id IN (123, 456, 7877)
如果这不能解决问题(例如,您确实希望每个 gu.id 类型为 aa 和 bb 和 cc(如果可用),那么请提供每个表的示例数据以完全代表您的问题。
评论
SELECT DISTINCT