gpt4 book ai didi

postgresql - postgres select count distinct返回意外的额外行

转载 作者:行者123 更新时间:2023-11-29 12:35:01 25 4
gpt4 key购买 nike

如果 session 中的 UID 多于用户中的 UID(显然不应该那样),那么我希望在运行最后一次选择时得到一个非空结果集,但我没有返回任何行- 这个结果对我来说没有逻辑意义......

select count(distinct(uid)) from users;

> 108736

select count(distinct(uid)) from sessions;

> 108737

select count(*) from sessions where uid not in (select uid from users);

> 0

为了完整起见:

select count(*) from users where uid not in (select uid from sessions);

> 0

我检查了空值:

select count( * ) from sessions where uid is null; 

> 0

select count( * ) from users where uid is null;

> 14

模式在 sqlalchemy 中定义,并在 session 表中包含一个外键:

uid = Column(Integer, ForeignKey('users.uid', use_alter=True, name='fk_uid'))

此模式是用于分析目的的静态转储,因此不会出现并发问题...

最佳答案

您的第三个查询与您认为的不同。

下面的查询说明了这个问题:

SELECT 1 NOT IN (SELECT unnest(ARRAY[NULL]::int[]));

返回 NULL ,因为它不能说如果 1 <> NULL .因此,在您的查询中,where 条件始终为 NULL ,因为 users包含 NULL uid.

我推荐使用 EXCEPT请务必在您的 session 表中找到罪魁祸首。

SELECT uid from sessions EXCEPT SELECT uid from users;

关于postgresql - postgres select count distinct返回意外的额外行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com