如果 id 在其他 table 中不存在,则获取不同的行并使用合并

get distinct row and use coalesce if id not exist in other table

我有两个表:

Job_Order

-id
-creation_date
-assigned_to
-job_ordertype
-client

Job_Order_Stage

-id
-stage
-date 
-job_order(foreign key to job_order)

我想获取 job_order 中的所有行,如果 id 在 Job_Order_Stage 中不存在,则将阶段设置为 0。如果在 job_order_stage 中找到相同的 job_order,我还想只获取带有 max(stage) 的行。我要怎么做?

我这里有查询:

SELECT 
    a.id,a.creation_date,
    e.user_name,c.operation,
    c.system_,d.name,
    Coalesce((s.stage), 0) as stage_name
FROM job_order a
INNER JOIN account b ON a.assigned_to=b.id
INNER JOIN job_order_type c ON a.job_order_type=c.id
INNER JOIN user e ON b.user=e.user_id
INNER JOIN client d ON a.client=d.id
LEFT JOIN job_order_stage s ON s.job_order = a.id

我对这个 sql 语句的问题是,它显示了所有作业订单及其具有不同阶段的副本。如何解决这个问题?

这个会得到你所有 job_orders job_order_stage

中没有的
select job_order.*
  from job_order
    left join job_order_stage
      on job_order.id = job_order_stage.job_order
  where job_order_stage.job_order is null;

这个让你的max(stage)工作在job_order_stage

select job_order.id, max(job_order_stage.stage)
  from job_order 
    inner join job_order_stage
      on job_order.id = job_order_stage.job_order
  group by job_order.id;

或者您是否希望将它们合并?应该是这样的:

select job_order.*, max(coalesce(job_order_stage.stage, 0)) stage
  from job_order
    left join job_order_stage
      on job_order.id = job_order_stage.job_order
  group by job_order.id

这利用/滥用了 mysqls 对 group by 的特殊处理,但在这种情况下应该没问题。

根据评论更新

select *
  from (
    select job_order.*, max(coalesce(job_order_stage.stage, 0)) stage
      from job_order
        left join job_order_stage
          on job_order.id = job_order_stage.job_order
      group by job_order.id
 ) q 
 where stage = 2;