TimG

请教一个带正则的 Sql 查询问题

  •  
  •   TimG · Nov 9, 2023 via Android · 2551 views
    This topic created in 1099 days ago, the information mentioned may be changed or developed.

    数据库是 PostgreSQL ,我使用了类似如下的查询:

    where A ~ 'regex'
    

    目前需要取补集的数据,我直接用not取反了:

    where not(A ~ 'regex')
    

    结果两次获取的记录总数小于数据总量,想问下各位大佬为什么会出现这种问题?怎么写才能取到补集呢?

    6 replies  •  2023-11-10 09:33:22 +08:00
    MoYi123
    MoYi123
    Nov 9, 2023
    1
    1. 有 null ?
    2. 转成 not in primary key, 或者用 except
    Terry166
    Terry166
    Nov 9, 2023
    2
    use !~ instead of not
    TimG
    TimG
    OP
    Nov 9, 2023 via Android
    3
    @MoYi123 确实是 null 的问题,谢谢!
    cookii
    cookii
    Nov 9, 2023
    4
    null 的问题,你用=和!=也会遇到
    gitrebase
    gitrebase
    Nov 9, 2023
    5
    又是一个案例,来说明列一定要 not null
    Terry166
    Terry166
    Nov 10, 2023
    6
    postgres 文档上显示取补集用 !~,刚才用查询计划看了一下,用 not 和 !~ 其实上一样的,比如:
    explain select * from accounts where not (owner ~ 'regex') and owner is not null
    output: Filter: ((owner IS NOT NULL) AND ((owner)::text !~ 'regex'::text))
    not 其实也是解释为 !~,并没有额外去掉 null ,两者是等价的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4568 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 06:31 · PVG 14:31 · LAX 22:31 · JFK 01:31
    ♥ Do have faith in what you're doing.