0

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

enter image description here

enter image description here

For e.g. here if I want to check all the tasks which do not have key 'A'.

3 Answers 3

2

use correlated subquery with 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')
Sign up to request clarification or add additional context in comments.

4 Comments

. . The only reason that I will not upvote this correct answer is because of the use of arbitrary letters for table aliases.
@GordonLinoff, it would be great if you explain why that is a problem, it would be easy for me to learn then
. . Abbreviations for table names facilitate reading the query. They are also stable if you take a query and modify the from clause. Arbitrary letters are quite hard to follow, because the reader has to continually refer to the from clause to figure out where the columns come from.
@GordonLinoff Your point is very valid, and moving forward I'll make an effort to keep in mind your suggestion for coding style.
1

With not exists:

select *
from task t
where not exists (
  select 1 from taskattributes
  where taskid = t.taskid and key = 'A'
)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.