MySQL merging two queries
I have the following table setup:
branches table:
...
manager_id
sales_manager_id
admin_manager_id
...
the above-mentioned columns contain the foreign key for the users table.
to complicate things I also have a branches_extra table:
branches_extra:
id
branch_id
user_id
position_id
which contains user_id, br开发者_StackOverflow中文版anch_id foreign keys for additional, staff that will be displayed on a branches contact page on a website. The porblem is that users are sometimes displayed more than once becuae they can have multiple positions/roles, I currently have 2 queries I am using to return the managers specified in the branches table and then the extra staff in the branches_extra table:
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
and for the extra staff:
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
I would like to merge the queries in to a single query and concat the "position" column instead of having multiple entries...
What you probably wanted was GROUP_CONCAT()
SELECT userid, GROUP_CONCAT(position SEPARATOR ', ')
FROM (
... position joining.
)
GROUP BY userid;
And use that query as a subquery inside of the larger query.
精彩评论