Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

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 
        ) ;
share|improve this answer
add comment
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 
    )
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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