选择使用公共标识符的最新记录

时间:2011-12-14 16:27:35

标签: php mysql doctrine

我在Doctrine 2.1中有一个类似的实体:

<?php

    /**
     * @Entity
     * @Table(name="my_records")
     */
    class Record
    {
        /**
         * @Id
         * @Column(name="record_id",type="integer")
         */
        private $id;

        /**
         * @Column(name="common_id",type="string")
         */
        private $commonId;

        /**
         * @Column(name="record_content",type="text")
         */
        private $content;
    }

使用这样的表数据:

record_id    common_id    record_content
---------    ---------    --------------
    1          abcd       abcd content
    2          efgh       efgh content
    3          ijkl       ijkl content
    4          abcd       abcd content updated
    5          ijkl       ijkl content updated

我的问题是如何获得所有最近的价值?假设record_id越高,记录越新。我期待的数据是:

record_id    common_id    record_content
---------    ---------    --------------
    2          efgh       efgh content
    4          abcd       abcd content updated
    5          ijkl       ijkl content updated

2 个答案:

答案 0 :(得分:0)

试试这个 -

SELECT t.* FROM mytable t
  JOIN (
    SELECT common_id, MAX(record_id) record_id FROM mytable GROUP BY common_id 
  ) t2
  ON t2.common_id = t.common_id AND t2.record_id = t.record_id

答案 1 :(得分:0)

一个可能的查询可能如下所示。

select record_id, common_id, record_content
  from my_records join
    (select common_id, max(record_id) as max_record 
      from my_records
      group by common_id) as max_records 
  on my_records.common_id = max_records.common_id