我有以下表設置:MySQL的合併兩個查詢
分支表:
...
manager_id
sales_manager_id
admin_manager_id
...
上述列包含用戶表的外鍵。
使事情變得複雜我也有一個branches_extra表:
branches_extra:
id
branch_id
user_id
position_id
包含USER_ID,branch_id額外的,工作人員外鍵,將在樹枝被顯示在網站上聯繫頁面。標誌是用戶有時會顯示多次becuae他們可以有多個職位/角色,我目前有2個查詢我用於返回分支表中指定的經理,然後branch_extra表中額外的工作人員:
SELECT CONCAT(xoops_users_extra.first_name, ' ', xoops_users_extra.last_name) AS full_name, , xoops_users_extra.profile_image_thumb, xoops_users.email,
CASE xoops_users_extra.main_userid
WHEN branches.manager_id THEN 'Manager'
WHEN branches.sales_manager_id THEN 'Sales Manager'
WHEN branches.admin_manager_id THEN 'Admin Manager'
WHEN branches.ops_manager_id THEN 'Ops Manager'
WHEN branches.export_manager_id THEN 'Export Manager'
WHEN branches.import_manager_id THEN 'Import Manager'
END AS position,
CASE xoops_users_extra.main_userid
WHEN branches.manager_id THEN 1
WHEN branches.sales_manager_id THEN 2
WHEN branches.admin_manager_id THEN 3
WHEN branches.ops_manager_id THEN 4
WHEN branches.export_manager_id THEN 5
WHEN branches.import_manager_id THEN 6
END AS sort_order
FROM (branches, xoops_users_extra, xoops_users)
WHERE ((branches.manager_id = xoops_users_extra.main_userid)
OR (branches.sales_manager_id = xoops_users_extra.main_userid)
OR (branches.admin_manager_id = xoops_users_extra.main_userid)
OR (branches.ops_manager_id = xoops_users_extra.main_userid)
OR (branches.export_manager_id = xoops_users_extra.main_userid)
OR (branches.import_manager_id = xoops_users_extra.main_userid))
AND xoops_users.uid = xoops_users_extra.main_userid
AND branches.branch_id = %d ORDER BY sort_order ASC
和額外的工作人員:
SELECT CONCAT(xoops_users_extra.first_name, ' ', xoops_users_extra.last_name) AS full_name,
positions.description AS position, xoops_users.email, xoops_users_extra.profile_image_thumb AS thumbnail
FROM (xoops_users, xoops_users_extra, branches_extra, branches, positions)
WHERE branches_extra.uid = xoops_users_extra.main_userid
AND positions.id = branches_extra.position
AND branches.branch_id = branches_extra.branch_id
AND xoops_users.uid = xoops_users_extra.main_userid
AND branches_extra.display =1
AND branches.branch_id = %d
我想在一個單一的查詢和CONCAT的「位置」一欄,而不是具有多個項目合併查詢...
總體模式尚不清楚。例如,xoops_users_extra表的這個main_userid字段是什麼?什麼是職位的表格字段等。順便說一句,我鼓勵你使用'明確的JOIN語法',因爲如果沒有別的東西,這樣的結構會引入「自我記錄」,使得分享(甚至是重新訪問) )查詢源代碼。 – mjv 2009-10-27 13:31:35
這是一個令人難以理解的混亂,我已recenlty被聘請維護;-p – 2009-10-27 13:33:12
沒關係,我想我會做一些數組muntering在php ... – 2009-10-27 13:33:59