1

我的数据库上有以下表格

数据库表

有几种项目状态(等待、工作、完成、已支付),一个项目必须经历从等待到已支付的所有状态。

为了完整跟踪项目,每个状态都被保留,所以我们知道项目何时改变了它的状态。

我想创建一个具有当前状态的搜索过滤器(具有更新的“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

4 回答 4

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
于 2013-10-08T13:27:05.077 回答
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

于 2013-10-08T13:35:53.903 回答
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)
于 2013-10-08T13:20:58.160 回答
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 
于 2013-10-08T13:25:56.637 回答