2011-12-14 60 views
0

我有一个是这样的教义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 

回答

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 
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