Search code examples
mysqljoinmaxdistinctcoalesce

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


I have two tables:

Job_Order

-id
-creation_date
-assigned_to
-job_ordertype
-client

Job_Order_Stage

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

I want to get all rows in the job_order and set stage to 0 if id not exist in the Job_Order_Stage. And I also want to get only the row with max(stage) if same job_order found in job_order_stage. How am I going to do it?

I have here the query:

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

My problem with this sql statement is that, it displays all job orders and its duplicate having different stage. How to fix this?


Solution

  • This one gets all your job_orders that aren't in 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;
    

    This one gets your max(stage) where the job IS in 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;
    

    Or did you somehow want them to be combined? Which would be something like this:

    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
    

    This makes use of / abuses mysqls special handling of group by, but in this instance it should be fine.

    update from comments

    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;