Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two query results into one and I have different column name

I have two queries I want to combine into a single output, I can't use a Union operator because they have different numbers of columns.

**First query result**

A1     A2

10     15

**Second query Result**

B1   B2

5      10

**The final result would be**

A1    A2     B1     B2

10    15     5       10

Thanks in advance

like image 956
Bhanu Avatar asked Oct 18 '25 07:10

Bhanu


1 Answers

If you only have one row from each query, it's just a CROSS JOIN

SELECT
  *
FROM
  (query1)   AS q1
CROSS JOIN
  (query2)   AS q2

If you have more than one row from each query, you need an INNER JOIN or maybe a FULL OUTER JOIN and some relationship between the two sets of data, so that you can tell the SQL engine which row joins to which row...

SELECT
  *
FROM
  (query1)   AS q1
FULL OUTER JOIN
  (query2)   AS q2
      ON  q2.id2 = q1.id1   -- Or some other predicate


Note:

  • UNION appends data vertically
  • JOIN appends data horizantally
like image 199
MatBailie Avatar answered Oct 20 '25 22:10

MatBailie