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

时间:2015-05-25 03:37:31

标签: mysql join max distinct coalesce

我有两张桌子:

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_Stage中不存在id,我想获取job_order中的所有行并将stage设置为0。如果在max(stage)中找到相同的job_order,我也希望仅使用job_order_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语句的问题是,它显示所有作业单及其副本有不同的阶段。如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这个获取所有不在job_order_stage中的job_orders

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;