我有两个具有 1-N 关系的实体,如下所示:
table_a
-------
id
name
table_b
------
id
table_a_id
name
status
created_at
我正在寻找一种在 MySQL 中,尤其是 Doctrine ORM 中使用 table_b 上的“where”子句查询 table_a 的方法,该子句仅影响最后一个关联的 table_b 记录。
假设我有以下记录:
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
所以我想告诉 MySQL/Doctrine : 给我 table_a 记录 其中有 table_b 记录 AND status = 1 在最后一个相关元素上(根据 created_at 字段)
这应该只返回:
table_a
----------------------------
id | name
----------------------------
1 | john
最佳答案
据书SQL Antipatterns ,这种具有适当索引的连接通常可以比子查询执行得更好。所以,也试试这个方法吧:
SELECT a.*
FROM table_a a
JOIN table_b b1
ON b1.table_a_id = a.id
AND b1.status = 1
LEFT JOIN table_b b2
ON b2.table_a_id = a.id
AND b2.created_at > b1.created_at
WHERE b2.table_a_id IS NULL
如果来自 table_b 的状态为 1
的两行具有相同的 table_a_id
和 created_at
日期,那么您将需要 DISTINCT
避免重复:
SELECT DISTINCT a.*
FROM table_a a
JOIN table_b b1
ON b1.table_a_id = a.id
AND b1.status = 1
LEFT JOIN table_b b2
ON b2.table_a_id = a.id
AND b2.created_at > b1.created_at
WHERE b2.table_a_id IS NULL
关于php - 根据最新的关联对象查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9431950/