How to combine two query results into one and I ha

2019-08-02 06:54发布

问题:

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

回答1:

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


回答2:

Here's a little trick:

SELECT *
FROM q1
LEFT JOIN q2 ON 1 = 1