select t.* from
(
SELECT p.*
,b.id as brand
,b.name as brandname
,j.id as closed
,c.name as customername
,l.name as productline
,u.user_name as username
,TIMESTAMPDIFF(HOUR,j1.start_date,j2.delivery_date) as total_hour
FROM `project` AS p
left join customer as c on c.id = p.customer
left join brand as b on b.id = c.brand
left join customer_product_line as l on l.id = p.product_line
left join users as u on u.id = p.created_by
left join (select project_id,`status`,id from job where `status` <> '1' group by project_id,`status`) as j on j.project_id = p.id
left join (select project_id,start_date from job where project_id = id order by start_date asc limit 1) as j1 on j1.project_id = p.id
left join (select project_id,delivery_date from job where project_id = id order by delivery_date DESC limit 1) as j2 on j2.project_id = p.id
) t
我在最后 2 个左连接中
p.id
有错误
任何通过函数或过程或其他方式来做到这一点的方法
您不能在
JOIN
中使用相关子查询。
无需在子查询中使用
ORDER BY <column> DESC LIMIT 1
,只需在其 MAX(<column>)
列表中使用 SELECT
即可。您可以使用单个查询来获取 MAX(start_date)
和 MAX(delivery_date)
。
SELECT p.*
,b.id as brand
,b.name as brandname
,j.id as closed
,c.name as customername
,l.name as productline
,u.user_name as username
,TIMESTAMPDIFF(HOUR,j1.max_start,j1.max_delivery) as total_hour
FROM `project` AS p
left join customer as c on c.id = p.customer
left join brand as b on b.id = c.brand
left join customer_product_line as l on l.id = p.product_line
left join users as u on u.id = p.created_by
left join (select project_id,`status`,id from job where `status` <> '1' group by project_id,`status`) as j on j.project_id = p.id
left join (
select project_id,MAX(start_date) AS max_start, MAX(delivery_date) AS max_delivery
from job
GROUP BY project_id
) as j1 on j1.project_id = p.id