0

我有 2 张桌子tasktaskattributes. 2个表之间有一个链接taskid。每个taskid都有多个由 表示的属性key,value。我想知道该任务是否存在特定密钥

在此处输入图像描述

在此处输入图像描述

例如,如果我想检查所有没有键“A”的任务。

4

3 回答 3

1

correlated subquery与_not exists

select a.taskid, b.key, b.value
from task a inner join taskattributes b on a.taskid=b.taskid
where not exist 
     (select 1 from taskattributes c on c.taskid=b.taskid and key='A')
于 2019-07-19T10:26:27.677 回答
1

not exists

select *
from task t
where not exists (
  select 1 from taskattributes
  where taskid = t.taskid and key = 'A'
)
于 2019-07-19T10:27:06.460 回答
0

一种简单的解决方案使用聚合:

SELECT
    t.taskid,
    t.name
FROM task t
INNER JOIN taskattributes ta
    ON t.taskid = ta.taskid
GROUP BY
    t.taskid,
    t.name
HAVING
    COUNT(CASE WHEN "key" = 'A' THEN 1 END) = 0;

如果您使用的是 Postgres 9.4 或更高版本,则可以FILTERHAVING子句中使用:

HAVING COUNT(*) FILTER (WHERE "key" = 'A') = 0
于 2019-07-19T10:27:35.790 回答