2013-10-08 92 views
1

我有我的數據庫如下表按日期和初級加入查詢

database tables

有幾個項目狀態(等待,工作,完成支付)和一個項目必須通過所有從等待到付款的狀態。

爲了保證項目的完整軌跡,每個狀態保持,所以我們知道當一個項目改變了它的地位。

我想創建一個搜索過濾器當前狀態(具有更近「created_at」)。

我試過幾次查詢,以獲得正確的結果,但我堅持這一個。

的不工作的查詢我是

select p.* from projects p 
left join projects_status_projects psp on psp.project_id = p.id 
where p.id in (select project_id from projects_status_projects 
     where project_status_id = XX group by project_id order by created_at desc) 

OFC,此查詢不工作,並與project_status_id XX記錄返回我的每個項目,沒有考慮帳戶的順序。

任何暗示將是非常讚賞!

感謝,
本傑明

+0

這並不需要有一個單獨的連接表( projects_status_projects),因爲每個項目狀態將只屬於一個項目(如果我已經正確地閱讀了這個問題)。 project_statuses表應該只有一個project_id列。這將使您的查詢更易於管理。 – Slicedpan

+0

@Slicedpan,也許我的問題沒有得到正確的刪節,但project_statuses表包含「狀態標籤」,如「支付,等待等等」(這使我們能夠增加新的狀態和避免常量)。 所以連接表需要 – bmichotte

回答

1
select p.* from projects p 
left join projects_status_projects psp on (psp.project_id = p.id) 
where created_at = (select max(created_at) 
        from projects_status_projects where 
        project_id = p.id)   

sqlfiddle一些例子在這裏:http://sqlfiddle.com/#!2/725fcc/7/0

+0

對於完整的查詢,我不得不添加'和project_status_id = XX' 感謝您的良好答覆。 – bmichotte

0

這裏是解決它的方法之一:

select p.* from projects p 
left join projects_status_projects psp on psp.project_id = p.id 
where p.id in (select project_id from projects_status_projects 
     where project_status_id = XX and created_at = min(created_at) group by project_id) 
+0

首先查詢不會放棄的結果 –

+0

你是對的,第一個是亂碼,所以我刪除它,只保留第二個。 –

+0

刪除-1現在... :-) –

0

試試這個:

select p.* from projects p 
    left join projects_status_projects psp on psp.project_id = p.id 
    where psp.id = (select max(id) from projects_status_projects 
      where projects_status_projects.project_id =p.id) and psp.project_status_id = XX 

select p.* from projects p,projects_status_projects psp 
    where psp.project_id = p.id and psp.id = (select max(id) from projects_status_projects 
      where projects_status_projects.project_id =p.id) and psp.project_status_id = XX 
1

如果你只需要在項目的當前狀態

試試這個::

Select DITINCT(p.id),p.* 
from projects p 
left join projects_status_projects psp on psp.project_id = p.id 
where project_status_id = XX 
order by created_at desc