根据最新的相关对象查询

时间:2012-02-24 13:58:05

标签: php mysql symfony doctrine

我有两个具有1-N关系的实体,如下所示:

table_a
-------
id
name

table_b
------
id
table_a_id
name
status
created_at  

我正在寻找MySQL中的方法,特别是使用Doctrine ORM来查询table_a,其中table_b上的“where”子句仅影响最后一个关联的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

2 个答案:

答案 0 :(得分:2)

根据书籍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_idcreated_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

答案 1 :(得分:0)

不确定“Doctrine”,但MySQL查询可能

select
      a.ID,
      a.Name
   from
      table_b B
         join table_a A
            on B.table_a_id = A.ID
   where
      B.status = 1
   order by
      B.Created_At DESC
   limit 1