2013-06-19 169 views
0

我試圖從兩個表doc_to_do及以下doc_bug_tracker列出最新更新兩個表和秩序是我的表結構選擇按日期

doc_to_do enter image description here

doc_bug_tracker enter image description here

這是我當前的查詢:

$sth = $this->db->prepare('SELECT p.*, 
     dtd.projects_id as dtd_projects_id, dtd.content as dtd_content, dtd.date_modified as dtd_date_modified, 
     dbt.projects_id as dbt_projects_id, dbt.content as dbt_content, dbt.date_modified as dbt_date_modified 
     FROM `projects` p LEFT JOIN `doc_to_do` dtd ON p.id=dtd.projects_id 
     LEFT JOIN `doc_bug_tracker` dbt ON p.id=dbt.projects_id 
     where p.id="'.$project_id.'"'); 

所以現在如何訂購date_modified無論是從表doc_to_dodoc_bug_tracker

回答

1

要獲得的最後日期(而不是所有的日期,有序的降序)試試這個:

SELECT 
    p.id, 
    MAX(GREATEST(dtd.date_modified, dbt.date_modified)) AS MaxDate 
FROM projects p 
LEFT JOIN doc_to_do dtd ON p.id = dtd.projects_id 
LEFT JOIN doc_bug_tracker dbt ON p.id = dbt.projects_id 
WHERE p.id = <project_id> 
GROUP BY p.id 

如果您需要在其他列的SELECT,請務必將它們包含在您的GROUP BY中。

0

這應該工作:

'SELECT x.* FROM 
(
    SELECT p.*, 
     dtd.projects_id as dtd_projects_id, dtd.content as dtd_content, dtd.date_modified as dtd_date_modified, 
     dbt.projects_id as dbt_projects_id, dbt.content as dbt_content, dbt.date_modified as dbt_date_modified 
     FROM `projects` p LEFT JOIN `doc_to_do` dtd ON p.id=dtd.projects_id 
     LEFT JOIN `doc_bug_tracker` dbt ON p.id=dbt.projects_id 
     where p.id="'.$project_id.'" 
) x 
ORDER BY x.date_modified ASC'