[eluser]Dracos[/eluser]
I have part of a query where I need to limit the results of table1 by whether they are related at least one of a given set of related table2 ids. The relationship of table1 to table2 is many to many, so there is a table1_table2 join table. I think the way to do this is a subquery, but I'm not sure how to achieve the result I need.
This query gives me the counts of the related table2 objects from table1:
Code:
SELECT
table1_alias.id,
table1_alias.title,
(
SELECT
count(*)
FROM
table1_table2 table1_table2_alias
WHERE
table1_table2_alias.table1_id = table1_alias.id
AND
table1_table2.table2_id in (398, 503, 718)
) AS tag_count
FROM
table1 table1_alias
HAVING
tag_count > 0;
This query accomplishes the same by moving the subquery to a where clause:
Code:
SELECT
table1_alias.id,
table1_alias.title
FROM
table1 table1_alias
WHERE
(
SELECT
count(*)
FROM
table1_table2 table1_table2_alias
WHERE
table1_table2_alias.table1_id = table1_alias.id
AND
table1_table2_alias.table2_id in (398, 503, 718)
) > 0;
I don't need the table2 counts in the result, just to limit the results according to the table1 objects being related to the given table2 ids.