MySQL:使用条件WHERE查询UNION,JOIN

时间:2016-03-10 04:26:45

标签: mysql sql join union

假设我们有以下表,employee和payroll_slip:

表:员工

 id_employee | name_employee |
    ============|===============|
    1           | john          |
    2           | doe           |
    3           | alex          |

表: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      |

我们希望在month_slip = '03'year_slip = '2016'

中获得以下结果
id_employee | month_slip | year_slip | status_slip
============|============|===========|============
1           | 03         | 2016      | paid
2           | 03         | 2016      | unpaid
3           | 03         | 2016      | paid

我尝试了这个查询:

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'

对此有何建议?

2 个答案:

答案 0 :(得分:1)

尝试此查询:

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'

这里的诀窍是将month_slipyear_slip 内的限制移到<{1}}条件中,而不是JOIN子句中

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:1)

尝试交叉加入:

 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