MySQL合并两个查询

时间:2009-10-27 13:07:04

标签: sql mysql

我有以下表格设置:

分支表:

...
manager_id
sales_manager_id
admin_manager_id
...

上述列包含users表的外键。

使事情变得复杂我还有一个branches_extra表:

branches_extra:

id
branch_id
user_id
position_id

其中包含user_id,branch_id外键以供其他人员使用,这些人员将显示在网站的分支机构联系页面上。问题是,用户有时会不止一次地显示他们可以拥有多个职位/角色,我目前有2个查询用于返回分支表中指定的经理,然后是branches_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

我想将查询合并到一个查询中并连接“position”列而不是多个条目......

1 个答案:

答案 0 :(得分:1)

你可能想要的是GROUP_CONCAT()

SELECT userid, GROUP_CONCAT(position SEPARATOR ', ') 
FROM (
   ... position joining.
) 
GROUP BY userid;

并将该查询用作较大查询中的子查询。