sql - postgresql::检索匹配精确条件的行或匹配部分条件的行数

标签 sql postgresql lazy-evaluation

我有像这样的表“权限”

| user_id | object_id | readable | writable |

我需要确定给定的 object_id 是否可以被当前的 user_id 访问,规则如下:

  • 如果根本没有object_id的记录,则返回true
  • 如果object_id有记录但user_id有记录,而给定的user_id没有记录,则返回false<
  • 如果给定的user_idobject_id有记录,则再次检查提供的可读可写条件

我不确定是否可以构建不涉及嵌套查询的 SQL 查询,现在我想出了

select (
    select count(*) 
    from permission 
    where 
        object_id = 123456
    ) == 0 OR (
        select readable=true, writable=false 
        from permission 
        where user_id=1 and object_id=123456
    )

有没有更优雅的解决方案?

谢谢!

最佳答案

尝试:

SELECT count(*) as total_count, --count of permission records for object
       bool_or(user_id = 1 AND readable) as user_readable, -- user has read permission, null if no permission record
       bool_or(user_id = 1 AND writable) as user_writable, -- user has write permission, null if no permission record
FROM permission
WHERE object_id = 123456

然后从这个查询中构建您的逻辑案例,例如:

SELECT total_count = 0 OR user_readable as readable,
       total_count = 0 OR user_writable as writable
FROM (first select here)

关于sql - postgresql::检索匹配精确条件的行或匹配部分条件的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973085/

相关文章:

php - Zend-Framework2。查询

postgresql - 在 Postgresql 中将 int 值转换为数字?

c# - 在 C# 中计算值的数组(从 Excel 转换公式)

python - Dask中compute()的目的

lazy-evaluation - 在 Orient-DB 中延迟执行查询

SQLite3 Group By 错误地仅返回 1 行

sql - 如何查找列中的连续值

sql - 使用动态 SQL 时列名无效

postgresql - 存储用户定义的段 JSONB 与单独的表?

php - pg_query() : Query failed: ERROR: more than one row returned by a subquery used as an expression