2009-12-16 53 views
2

我有两个表“系列”和“程序”,程序是多对一的系列。有限制的关系表的学说秩序

系列表

id | name 
-------------- 
1 | lorem 
2 | ipsum 
3 | foo 
4 | bar 

计划表

id | name  | series_id 
--------------------- 
1 | program1 | 1 
2 | program2 | 2 
3 | program3 | 3 
4 | program4 | 4 
5 | program5 | 1 
6 | program6 | 2 
7 | program7 | 3 
8 | program8 | 4 
9 | program9 | 1 
10 | program10 | 2 
11 | program11 | 1 
12 | program12 | 2 

我想学说(1.2)与最新的程序,以获得两个系列,在这种情况下,系列2,然后是系列1,请参阅程序中的最后两行。

我的猜测是:

$q = Doctrine_Query::create()->from('Series s') 
          ->leftJoin('s.Programs p') 
          ->orderBy('p.id desc') 
          ->limit(2); 

但这返回系列4和系列3的问题是,这种理论会使用不同的查询得到的ID在做其中的数据将包括在查询之前,他们使用该策略,因为我认为MySql不能在子查询中使用限制。

我的问题,你会如何获得系列2系列1通过DQL?

回答

1

试试这个:

$q = Doctrine_Query::create() 
    ->select('s.name') 
    ->addSelect('(SELECT p.series_id FROM Programs p WHERE p.series_id = s.id) as series_name') 
    ->from('Series s'); 
    ->orderBy('p.id desc') 
    ->limit(2);