Combine Multiple Query Results in MySQL (by column)

后端 未结 2 1912
轻奢々
轻奢々 2020-12-19 10:04

I have 4 different queries and each of them return individual unique set of Results. I need to combine the Query Results with using a single query.

my sample queries

相关标签:
2条回答
  • 2020-12-19 10:43

    I assume you want your example to return a single row combining the corresponding entries from all these tables. Try this and tell us if it worked:

    select * from users as usr
    left outer join (calls as cls 
        inner join calls_users as clsusr 
        on cls.id = clsusr.call_id) 
    on usr.id = cls.assigned_user_id 
    
    left outer join (meetings as mtn 
        inner join meetings_users as mtnusr 
        on mtn.id = mtnusr.meeting_id) 
    on usr.id = mtn.assigned_user_id 
    
    left outer join tasks as tsk 
    on usr.id = tsk.assigned_user_id 
    
    left outer join (notes as nts 
        inner join accounts as acnts 
        on acnts.id=nts.parent_id) 
    on usr.id = acnts.assigned_user_id 
    
    where user.id = 'seed_max_id'
    
    0 讨论(0)
  • 2020-12-19 10:44

    The best you can do is a UNION or UNION ALL but this requires them to have the same type and number of columns. For example:

    SELECT 'Customer' AS type, id, name FROM customer
    UNION ALL
    SELECT 'Supplier', id, name FROM supplier
    UNION ALL
    SELECT 'Employee', id, full_name FROM employee
    

    The column names don't have to match. The aliases from the first part will be used for the rest.

    I'll also add that instead of:

    select cls.* from (calls as cls inner join calls_users as clsusr on cls.id=clsusr.call_id) inner join users as usr on usr.id=cls.assigned_user_id where cls.assigned_user_id='seed_max_id'
    

    you should remove the unnecessary subquery and just do:

    SELECT c.*
    FROM calls c
    JOIN calls_users cu ONc.id = cu.call_id
    WHERE c.assigned_user_id = 'seed_max_id'
    

    There's no need for the extra complexity and the above is eminently more readable.

    0 讨论(0)
提交回复
热议问题