1

I have two tables, a Project and an Action:

Project has the following fields:

project_name

Action has the following fields:

action_name
project
status

There is a one-to-many relationship between Action and Project.

I need a query that returns all the Projects that ONLY have actions with statuses greater than 1 OR Projects with no actions at all.

I've never written a query that is dependent on a relationship. How might this be constructed?

3

Your solution seems correct. Here's another way that may be more efficient as it doesn't do a grouping. It can't show the MIN(status) though:

SELECT
    "id", "name" 
FROM 
    "testapp_project" AS p
WHERE
    NOT EXISTS
        ( SELECT *
          FROM "testapp_action" AS a
          WHERE p."id" = a."project_id"
            AND a."status" <= 1 
        ) ;
1
SELECT
    "testapp_project"."id", "testapp_project"."name", 
    MIN("testapp_action"."status") AS "m" 
FROM 
    "testapp_project" 
    LEFT OUTER JOIN "testapp_action" ON
        ("testapp_project"."id" = "testapp_action"."project_id")
    GROUP BY "testapp_project"."id", "testapp_project"."name" 
    HAVING(
       MIN("testapp_action"."status") IS NULL 
         OR
       MIN("testapp_action"."status") > 1 
    )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.