我不知道如何將兩個表連接到我的主查詢上。決定accountnumber的兩個表連接到三個主表中的每一個,用於不同的情況。MYSQL一個大的左外連接還是3個左外連接同一個表?
我想根據三件事來確定帳號。 accountnumber基於三個不同表格的支付代碼,部門和員工類型。
以下是他們應該如何加入。
/* all accountnumbers have a paycode_id*/
accountcodes.paycode_id = employee_pay.id
/* all accountnumbers are assigned to either a certain department or all*/
accountcodes.department_code = department.code
/* the accountnumber can be assigned to one emp_type or both*/
accountcodes.emp_type_id = employee_infos.emp_type_id
/* the accountnumber is in table:lkp_accountcodes, that determines the account number table:accountcodes */
accountcodes.lkp_accountcodes_id = lkp_accountcodes.id
表:accountcodes
-----------------------------------------------------------------------
| ID | lkp_accountcodes_id | paycode_id | department_code | emp_type_id |
|--------------------------|------------|-----------------|-------------|
| 1 | 21 | 15 | 120 | 1 |
| 2 | 22 | 15 | 310 | 1 |
| 3 | 23 | 30 | null | 1 |
| 4 | 24 | 30 | null | 2 |
| 5 | 25 | 55 | 120 | 1 |
| 6 | 26 | 55 | 310 | 2 |
| 7 | 27 | 55 | 120 | 2 |
-----------------------------------------------------------------------
表:lkp_accountcodes
-----------------------------------
| id | company_id | accountnumber |
|-----|------------|----------------|
| 21 | 500 | 5210 |
| 22 | 500 | 6210 |
| 23 | 500 | 2211 |
| 24 | 500 | 2210 |
| 25 | 500 | 5010 |
| 26 | 500 | 6000 |
| 27 | 500 | 5090 |
-----------------------------------
我不知道我應該做的左邊三個連接,創建臨時表,或一個大的左外加入如下所示? 另外,我不確定如何對它進行分組,如果離開的代碼爲空,那麼accountnumber應該由paycode_id和emp_type_id確定。 請幫我看下面的查詢。
SELECT i.employee, d.department, e1.paycode, a1.accountnumber
FROM employee_pay e1
INNER JOIN employee_infos i ON e1.emp_info_id = i.id
INNER JOIN department d ON i.department_id = d.id
LEFT OUTER JOIN accountcodes ac ON ac.paycode_id = e1.id
AND ac.emp_type_id = i.emp_type_id
AND ac.department_code = d.code -- if null?
LEFT OUTER JOIN lkp_accountcodes lgc on gp.lkp_gl_code_id = lgc.id
-- group?
預期的結果
emp_number | emp_type | deptartment | pay_code | account_number
123 | temp | 120 | CPP Ded | 5210
456 | reg | 310 | CPP Ded | 6210
789 | temp | null | ExpReim | 2210
987 | reg | null | ExpReim | 2211
654 | reg | 145 | StatHol | 5010
321 | temp | 145 | StatHol | 5090
333 | temp | 532 | StatHol | 6000
更新你的問題,並添加expetced結果的事實,請 – scaisEdge
@scaisEdge添加 –