我有3张桌子,分别是 - 区域,作品和工作。
areas works jobs
----- ----- -----
area_id work_id area_id (FK)
area_name task work_id (FK)
area_type app_area status
updated_at
我正在尝试选择与作品交叉加入的区域的总列表,以便我具有区域与作品的所有排列,然后具有该组合的最新状态(如果存在)。我希望每个area_id-work_id组合都有不同的行。
我把下面的查询语句放在一起,但有些行的状态在实际存在时显示为NULL。我的猜测是我的内部SELECT语句出了问题,但是尽可能地尝试,我无法让它工作,不知道我的陈述有什么问题吗?
SELECT area_name, works.task, jobs.status
FROM areas
CROSS JOIN works ON works.work_id = works.work_id
LEFT JOIN jobs ON jobs.status = (SELECT jobs.status FROM jobs ORDER BY jobs.updated_at DESC LIMIT 1) AND
(jobs.work_id = works.work_id AND jobs.area_id = areas.area_id)
WHERE works.app_area = 'zone' AND areas.area_type = 'zone'
ORDER BY areas.area_id, works.work_id, jobs.updated_at;
答案 0 :(得分:0)
您上次状态的逻辑应使用日期而不是状态。逻辑如下:
SELECT a.area_name, w.task, j.status
FROM areas a CROSS JOIN
works w LEFT JOIN
jobs j
ON j.work_id = w.work_id AND j.area_id = a.area_id AND
j.updated_at = (SELECT MAX(j2.updated_at)
FROM jobs j2
WHERE j2.work_id = w.work_id AND j2.area_id = a.area_id
)
WHERE w.app_area = 'zone' AND a.area_type = 'zone'
ORDER BY a.area_id, w.work_id, j.updated_at;
这也解决了一些其他问题,例如ON
条款CROSS JOIN
。
答案 1 :(得分:0)
如果您想通过自己的查询解决它,请在左连接子查询中替换此行
SELECT j.status FROM jobs j ORDER BY jobs.updated_at DESC LIMIT 1
答案 2 :(得分:0)
使用戈登解决方案,我认为这是你可以做到的另一种方式。你必须进行测试,看看哪种方式对你来说更快。
SELECT a.area_name, w.task, (SELECT MAX(j2.updated_at)
FROM jobs j2
WHERE j2.work_id = w.work_id AND j2.area_id = a.area_id
) status
FROM areas a CROSS JOIN
works w LEFT JOIN
jobs j
ON j.work_id = w.work_id AND j.area_id = a.area_id
WHERE w.app_area = 'zone' AND a.area_type = 'zone'
ORDER BY a.area_id, w.work_id, j.updated_at;