如何使用左外连接交叉连接?

时间:2014-06-04 06:54:16

标签: mysql

我必须显示特定月份的费用索赔员工列表,但我要获得所有员工列表。

SELECT employee_id, expense_month, GROUP_CONCAT(CONCAT_WS('=', exp_type_text, monthly_exployee_expense))
FROM
(
SELECT tbl_employee.employee_id, expense_months.expense_month, tbl_expense_type.exp_type_id, tbl_expense_type.exp_type_text, SUM(expense_cost) AS monthly_exployee_expense
FROM tbl_employee
CROSS JOIN tbl_expense_type
CROSS JOIN
(
    SELECT DISTINCT DATE_FORMAT(expense_date, '%Y%m') AS expense_month
    FROM exp_tbl
) expense_months
LEFT OUTER JOIN exp_tbl
ON tbl_employee.employee_id = exp_tbl.employee_id
AND tbl_expense_type.exp_type_id = some_table.expense_type
AND expense_months.expense_month = DATE_FORMAT(exp_tbl.expense_date, '%Y%m')
GROUP BY tbl_employee.employee_id, expense_months.expense_month, tbl_expense_type.exp_type_id, tbl_expense_type.exp_type_text
) Sub1
GROUP BY employee_id, expense_month

这个查询我有..如何只获得费用索赔员工名单。

示例输出是:

3   Ramesh Kumar M  201402  Phone Expense=0=16,Consumable Purchase=0=11,Auto=0...
3   Ramesh Kumar M  201403  Consumable Purchase=0=11,Auto=0=6,2 wheeler=0=1,Lo...
3   Ramesh Kumar M  201404  Logistics/Transportation=0=18,Labour=0=13,Fuel=0=8...
3   Ramesh Kumar M  201405  Bus Travel=0=3,Office Vehicle=0=20,Others=0=15,Sta...
4   testexplevel1   201402  Others=0=15,Stay=0=10,Train Travel=0=5,Office Main...
4   testexplevel1   201403  Office Maintenance=0=17,Billable Purchase=0=12,Cal...
4   testexplevel1   201404  Call Taxi=0=7,4 wheeler=0=2,Guest House=0=19,Trans...

在该列表中不希望所有员工列表。仅显示ramesh数据。因为该员工只声称。

1 个答案:

答案 0 :(得分:0)

有道理。您将所有月份和所有费用类型的所有员工加入到一个大型笛卡尔产品中。然后你left join实际费用,如果没有费用,就不会排除任何费用。

因此,快速解决方案是inner join费用。这样做只会为您提供费用存在的员工月数。

但这样做也允许你完全删除交叉连接并将其全部更改为内部连接:

select
  emp.employee_id,
  DATE_FORMAT(ex.expense_date, '%Y%m'),
  GROUP_CONCAT(CONCAT_WS('=', et.exp_type_text, ex.monthly_exployee_expense))
from
  tbl_employee emp
  inner join exp_tbl ex on ex.employee_id = emp.employee_id
  inner join tbl_expense_type et on et.exp_type_id = ex.expense_type
group by
  emp.employee_id,
  DATE_FORMAT(ex.expense_date, '%Y%m')

现在,这个查询不是更干净吗? :)