按日期和主要加入查询

时间:2013-10-08 13:16:31

标签: mysql sql

我的数据库中有以下表格

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的记录,而不考虑订单。

任何暗示都会非常感激!

谢谢,
本杰明

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分: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