Reputation: 58
Say we have the following tables, employee and payroll_slip:
Table: employee
id_employee | name_employee |
============|===============|
1 | john |
2 | doe |
3 | alex |
Table: payroll_slip
id_slip | id_employee | month_slip | year_slip |
========|=============|============|===========|
1 | 1 | 01 | 2016 |
2 | 2 | 01 | 2016 |
3 | 1 | 02 | 2016 |
4 | 2 | 02 | 2016 |
5 | 1 | 03 | 2016 |
6 | 3 | 03 | 2016 |
And we want to get the following result where month_slip = '03'
AND year_slip = '2016'
id_employee | month_slip | year_slip | status_slip
============|============|===========|============
1 | 03 | 2016 | paid
2 | 03 | 2016 | unpaid
3 | 03 | 2016 | paid
I tried this query:
SELECT
a.id_employee,
payroll_slip.month_slip,
payroll_slip.year_slip,
IF(a.id_employee=payroll_slip.id_employee, 'paid', 'unpaid') AS status_slip
FROM (
SELECT id_employee FROM employee
UNION
SELECT id_employee FROM payroll_slip
) a
LEFT OUTER JOIN payroll_slip ON a.id_employee = payroll_slip.id_employee
LEFT OUTER JOIN employee ON a.id_employee = employee.id_employee
WHERE payroll_slip.month_slip = '03' AND payroll_slip.year_slip = '2016'
Any suggestion for this?
Upvotes: 1
Views: 69
Reputation: 825
Try having a cross join:
SELECT X.id_employee, X.month_slip, X.year_slip
, CASE WHEN Y.id_employee IS NULL THEN 'Unpaid' ELSE 'Paid' END AS status_slip
FROM (
SELECT A.id_employee, B.month_slip, B.year_slip
from employee A
cross join (
select '03' AS month_slip, '2016' AS year_slip
) B
) X
LEFT JOIN payroll_slip Y
ON X.id_employee = Y.id_employee
AND X.month_slip = Y.month_slip
AND X.year_slip = Y.year_slip
Upvotes: 1
Reputation: 521249
Try this query:
SELECT e.id_employee, '03' AS month_slip, '2016' AS year_slip,
CASE WHEN p.id_employee IS NOT NULL THEN 'paid' ELSE 'unpaid' END AS status_slip
FROM employee e LEFT JOIN payroll_slip p
ON e.id_employee = p.id_employee AND p.month_slip = '03' AND p.year_slip = '2016'
The trick here is to move the restrictions on the month_slip
and year_slip
inside the JOIN
condition, rather than in the WHERE
clause.
Follow the link below for a running demo:
Upvotes: 1