I have 2 tables task and taskattributes. There is a linking between 2 tables with taskid. Each taskid has multiple attributes represented by key,value.
I would like to find out if specific key exists for the task
For e.g. here if I want to check all the tasks which do not have key ‘A’.
Advertisement
Answer
One simple solution uses aggregation:
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;
If you are using Postgres 9.4 or later, you may use FILTER in the HAVING clause:
HAVING COUNT(*) FILTER (WHERE "key" = 'A') = 0

