0

Im struggling to join two tables that might output some null value

here is my 1st table named: Leave_Type

id  name            days_entitled
1   Vacation leave   12
2   Sick leave       12
3   maternity leave  5
4   paternity leave  5

Leave Details

requester_id requester_name leave_type_id   days_consumed
1            John           1               1   
1            John           2               3
1            John           1               1

Id like to see the result for requester John

id  name            days_entitled   days_consumed
1   Vacation leave   12             2
2   Sick leave       12             3
3   maternity leave  5              0
4   paternity leave  5              0

3 Answers 3

1

You can get the desired result as

select 
lt.*,
coalesce(x.days_consumed,0) as days_consumed
from leave_type lt 
left join ( 
  select leave_type_id, 
  sum(days_consumed) as days_consumed 
  from leave_details 
  where requester_id = 1 group by leave_type_id
)x on x.leave_type_id = lt.id 
Sign up to request clarification or add additional context in comments.

Comments

1

Try to using left join

select id,name,days_entitled, ifNull(days_consumed,0) from
Leave_Type left outer join Leave_Details on leave_type_id = id

3 Comments

i can get the same value if I filter the query (where requester_id=1)
what if John has two entry of same leave type like 2 ?
@Keval Then OP have to use group by and sum function. But it is not ask in the question as i can see.
0

Great.

select `requester`, tbl_hr_leave_type.id,name,`days_entitled`,sum(days) as Credit from
tbl_hr_leave_type left outer join tbl_hr_leave_form on tbl_hr_leave_form.`leave_details` = tbl_hr_leave_type.id and requester='411'
group by name
order by tbl_hr_leave_type.id 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.