I have two entities with an 1-N relation, like this :
table_a
-------
id
name
table_b
------
id
table_a_id
name
status
created_at
I’m looking for a way in MySQL and especially with Doctrine ORM to query table_a with a “where” clause on table_b that affect only the last associated table_b record.
Supposing I have the following records :
table_a
----------------------------
id | name
----------------------------
1 | john
2 | mary
3 | chuck
table_b
--------------------------------------------------
id | table_a_id | name | status | created_at
--------------------------------------------------
1 | 1 | blue | 1 | 2000-01-01
2 | 1 | red | 1 | 2012-12-31
3 | 2 | yellow | 1 | 2000-01-01
4 | 2 | green | 0 | 2012-12-31
So I want to tell MySQL/Doctrine :
GIVE ME the table_a records
WHICH HAVE table_b records
AND status = 1 ON the last related elements (according to the created_at field)
This should only return :
table_a
----------------------------
id | name
----------------------------
1 | john
According to the book SQL Antipatterns, this type of join with the proper indexes can often perform better than a subquery. So, try this method out too:
If there could be two rows from table_b with status
1that have the sametable_a_idandcreated_atdate, then you will needDISTINCTto avoid duplicates: