Joining the result of two queries mysql

后端 未结 5 681
刺人心
刺人心 2021-01-20 16:06

Without actually giving all the details of my query: Is there a way of joing the results of two separate queries on different tables? for example if i had a table

re

相关标签:
5条回答
  • 2021-01-20 16:43

    Completing @Microgen's answer... Since you already have your two first select working as you want, you can keep those results in temporary tables:

    create temporary table tmp1 as <your first select>;
    alter table tmp1 add <some index to accelerate your join later>;
    create temporary table tmp2 as <your second select>;
    alter table tmp2 add <some index to accelerate your join later>;

    Then, you could apply a simple join to get your final result:

    select tmp1.id, tmp1.name, tmp1.address, tmp2.occupation
        from tmp1 inner join tmp2 using (id)
        order by tmp1.id;

    Another way to do it is to use VIEW, but since the indexing is not the best thing they have, I would avoid them, specially when your first two select are as complex.

    0 讨论(0)
  • 2021-01-20 16:52

    I strongly suggest posting your SQL so a proper solution can be achieved. That is to say you should do this with MySQL instead of PHP.

    However, you will need to loop over your first set of records and build an array. Then loop over the second, appending it to the first set where the id matches.

    0 讨论(0)
  • 2021-01-20 16:59

    use temporary tables for the first two tables then use them to do the join but i guess you may have problem because there is no common attribute to join upon unless you wish to use the ids of the tables if they happen to match

    0 讨论(0)
  • 2021-01-20 16:59

    Begin with something like

    SELECT tablea.id,tablea.name,tablea.address,tableb.occupation
    

    and put something like this in the WHERE clause:

    WHERE tablea.id = tableb.id
    

    I don't think that you need a left join here.

    0 讨论(0)
  • 2021-01-20 17:10

    None of this (temp tables, joining two result sets) is necessary.

    You are much better off writing queries directly from your source tables. Not only for performance reasons (1 query is obviously better than 2 joined queries plus one), but for your understanding and progress.

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