为什么去相关查询没有产生预期的结果?

Why does the decorrelated query not produce expected result?

我正在尝试取消关联此相关查询:

select c1.c_name
    from customer c1
    where c1.c_mktsegment = 'AUTOMOBILE' or c1.c_acctbal >
    (select avg(c2.c_acctbal)
        from customer c2
        where c2.c_mktsegment = c1.c_mktsegment
    );

我的解决方案是这样的:

select c1.c_name from customer c1, 
(select c_mktsegment, avg(c_acctbal) as m from customer group by c_mktsegment) c2 
where 
c1.c_mktsegment = 'AUTOMOBILE' or 
(c1.c_acctbal > c2.m and c1.c_mktsegment=c2.c_mktsegment);

但我遇到的问题是,同一个 c_name 我得到了多个副本。我不确定我哪里做错了。

Here 是数据集架构。

要使这些查询等效,您需要对每一行使用连接条件 c1.c_mktsegment=c2.c_mktsegment。通过使其成为 OR 的一部分,您将 c1 的每一行(其中 c1.c_mktsegment = 'AUTOMOBILE' 连接到 c2 的每一行,而不管 c2.c_mkrsegment 是什么。

我相信这就是你想要的:

select c1.c_name from customer c1, 
(select c_mktsegment, avg(c_acctbal) as m from customer group by c_mktsegment) c2 
where 
c1.c_mktsegment=c2.c_mktsegment
AND
(c1.c_mktsegment = 'AUTOMOBILE' OR c1.c_acctbal > c2.m)

如果您使用更好的 inner join 语法,问题可能会更清楚:

select c1.c_name from customer c1 INNER JOIN
(select c_mktsegment, avg(c_acctbal) as m from customer group by c_mktsegment) c2 
 ON c1.c_mktsegment=c2.c_mktsegment
WHERE
c1.c_mktsegment = 'AUTOMOBILE' OR c1.c_acctbal > c2.m