【问题标题】:specifying count in WHERE clause在 WHERE 子句中指定计数
【发布时间】:2023-03-10 18:31:01
【问题描述】:
select *
from table1 t1,
    table2 t2,
    table3 t3
where t2.parent_id = t1.row_id
    and t2.xyz is not null
    and (
        select count(*)
        from table3
        where xyz = t2.row_id
        ) = 0;

它会起作用吗? 我在子查询中使用别名 t2。

我的要求是检查是否在 where 子句中指定条件,以便 table3 中不存在记录,其中 table3 的列 xyz 存储为 table2 的 row_id。

【问题讨论】:

  • 您使用的是什么版本的 SQL,您自己尝试过吗?我可能会使用 WHERE NOT EXISTS 而不是 count 子查询。请注意,您当前正在 table2table3 之间进行交叉连接,这可能不是您想要的。
  • 这可能在 Stack Exchange 子站点代码审查中
  • 今日提示:切换到现代、明确的JOIN 语法! (如下面@GurV 的回答。)

标签: sql count where


【解决方案1】:

您可以使用NOT EXISTS 断言没有从子查询返回的行。使用现代显式连接语法而不是基于逗号的传统语法。无需在外部加入 table3(您正在有效地进行交叉连接)。

select *
from table1 t1
join table2 t2 on t2.parent_id = t1.row_id
where t2.xyz is not null
    and not exists (
        select 1
        from table3
        where xyz = t2.row_id
        );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多