Select from multiple tables without a join?

后端 未结 8 1151
轻奢々
轻奢々 2020-12-05 01:53

What is the easiest way to select data from two tables and rather than join them, have them appear as separate rows. Both tables have similar or matching fields and I want t

8条回答
  •  一整个雨季
    2020-12-05 01:58

    The UNION ALL operator may be what you are looking for.

    With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).

    The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.

    SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
    UNION ALL
    SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
    UNION ALL
    SELECT 'q3', '1', '2', buckle, my_shoe FROM t4
    

    You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.

    SELECT t.a
         , SUM(t.b)
         , AVG(t.c)
      FROM (
             SELECT 'q1' AS source, a, b, c, d FROM t1
              UNION ALL
             SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
           ) t
     GROUP BY t.a
     ORDER BY t.a
    

提交回复
热议问题