From: | Niklas Johansson <spot(at)tele2(dot)se> |
---|---|
To: | PostgreSQL Admin <postgres(at)productivitymedia(dot)com> |
Cc: | PostgreSQL SQL List <pgsql-sql(at)postgresql(dot)org> |
Subject: | Re: Design and Question |
Date: | 2008-07-10 16:46:02 |
Message-ID: | 19B914A0-3C34-4AE6-9063-EC5F39FADFA5@tele2.se |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On 10 jul 2008, at 14.50, PostgreSQL Admin wrote:
> How do I combine the two in a query?
If you're looking for recipes that match *either* criterion (season
*or* diet), you could add the two subqueries generating the ids using
UNION or UNION ALL:
SELECT title FROM recipes WHERE id IN (
SELECT recipe_id FROM recipes_season WHERE season IN ('P', 'W')
UNION [ALL]
SELECT recipe_id FROM recipes_diet WHERE diet IN ('P')
);
or, you could use joins:
SELECT title FROM recipes r
LEFT JOIN recipes_season rs ON r.id=rs.recipe_id
LEFT JOIN recipes_diet rd ON r.id=rd.recipe_id
WHERE rs.season IN ('P', 'W') OR rd.diet IN ('P');
If, on the other hand, you're looking for recipes that match *both*
criteria, use:
SELECT title FROM recipes WHERE id IN (SELECT recipe_id FROM
recipes_season WHERE season IN ('P', 'W'))
AND id IN (SELECT recipe_id FROM recipes_diet WHERE diet IN ('P'));
or:
SELECT title FROM recipes r
INNER JOIN recipes_season rs ON r.id=rs.recipe_id
INNER JOIN recipes_diet rd ON r.id=rd.recipe_id
WHERE rs.season IN ('P', 'W') AND rd.diet IN ('P');
The optimal execution plan will be dependent on the size and
distribution of your data, so you should test the queries with real
data.
Sincerely,
Niklas Johansson
From | Date | Subject | |
---|---|---|---|
Next Message | Marcin Krawczyk | 2008-07-11 06:03:13 | record type |
Previous Message | Scott Marlowe | 2008-07-10 15:44:19 | Re: Converting Copy to insert statement in backup file |