94

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 to run some aggregate function on them such as avg all the rows that occurred in the same month, from both tables.

for example I have two tables, one that is shows transactions from one system and another with transactions from a different system. Is there a way to grab all the transactions from both tables as separate rows? if table 1 had twenty records and table 2 have thirty records, I'd like there to be 50 rows on the return.

Nicholas Hazen
  • 1,245
  • 2
  • 9
  • 13

10 Answers10

74

You could try something like this:

SELECT ...
FROM (
    SELECT f1,f2,f3 FROM table1
    UNION
    SELECT f1,f2,f3 FROM table2
)
WHERE ...
Asahi
  • 13,378
  • 12
  • 67
  • 87
Marco
  • 56,740
  • 14
  • 129
  • 152
  • 3
    the answer is under one column – Adarsh M Pallickal Jul 16 '14 at 04:22
  • 3
    @AdarshMPallickal: I don't understand you comment, sorry... what do you mean? – Marco Jul 16 '14 at 08:51
  • when i use union all results comes under one column – Adarsh M Pallickal Jul 16 '14 at 10:09
  • my situation is different – Adarsh M Pallickal Jul 16 '14 at 11:43
  • 7
    @AdarshMPallickal: if your situation is different, then post a question showing your situation and your needs... – Marco Jul 16 '14 at 17:06
  • sorry @Marco i don't have the permission to ask question. – Adarsh M Pallickal Jul 17 '14 at 03:48
  • 5
    You may want to use UNION ALL, in case the two tables have identical data column-wise. The OP seems to want ALL records from both tables to show. – banncee Feb 21 '17 at 21:12
  • @banncee: Good point. The `UNION` operation will collapse *all* duplicate rows in the resultset. Those duplicate rows could be coming from two different SELECTs, but they could also be from just one of the SELECTs. The `UNION` operation doesn't make a distinction. It collapses *all* of the duplicate rows in the set. The **`UNION ALL`** set operator avoids that (sometimes very expensive) operation of identifying and collapsing duplicates. – spencer7593 Feb 22 '17 at 19:31
54

You could try this notattion:

SELECT * from table1,table2 

More complicated one :

SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse

Such queries are usually called "implicit JOINs" and Explicit vs implicit SQL joins asks how both compare. In some cases implicit query execution planning is identical to explicit JOINs.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
wojciechz
  • 1,086
  • 8
  • 16
47

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
spencer7593
  • 106,611
  • 15
  • 112
  • 140
16

If your question was this -- Select ename, dname FROM emp, dept without using joins..

Then, I would do this...

SELECT ename, (SELECT dname 
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP

Output:

ENAME      DNAME
---------- --------------
SMITH      RESEARCH
ALLEN      SALES
WARD       SALES
JONES      RESEARCH
MARTIN     SALES
BLAKE      SALES
CLARK      ACCOUNTING
SCOTT      RESEARCH
KING       ACCOUNTING
TURNER     SALES
ADAMS      RESEARCH

ENAME      DNAME
---------- --------------
JAMES      SALES
FORD       RESEARCH
MILLER     ACCOUNTING

14 rows selected.
Vinay Kumar
  • 181
  • 1
  • 4
  • This is the only answer that actually worked for me as I'm currently trying to migrate a database to Azure and it contains old style join syntax (which is not allowed in Azure). Most joins are simple to change the syntax of, however SELECT [tab1].[col1], [tab2].[col1] FROM [tab1],[tab2] isn't easy when they don't share a column to join on. – JasperMoneyshot Aug 08 '19 at 08:56
  • 1
    it's a join. You've just used older syntax. – Marek Marczak Sep 14 '19 at 06:04
  • 1
    worked for me since I didn't have anything to join on, I just needed external info and didn't want a second query for one datapoint. – Brian Crawford Dec 11 '20 at 20:15
  • May i know what this method is called as i know this method is much faster then join or union – insoftservice Oct 27 '21 at 18:46
  • @insoftservice, I believe this is a correlated subquery. More info at [DoFactory.com](https://www.dofactory.com/sql/subquery). I would caution you on large queries, however. I believe performance can suffer when the subquery is run against a large working set. – Troy Sep 14 '22 at 11:49
  • Thanks @Troy . But many claims that by using this method performance of query increases instead of traditional join method. is it true do you have some more information or some links for it. It would be really helpful – insoftservice Sep 16 '22 at 06:01
11

You should try this

 SELECT t1.*,t2.* FROM t1,t2
3

SELECT * from table1 UNION SELECT * FROM table2

esenkaya
  • 99
  • 4
2

Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

Kunchok Tashi
  • 2,413
  • 1
  • 22
  • 30
0

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

Lin W
  • 289
  • 4
  • 4
-1

In this case we are assuming that we have two tables: SMPPMsgLogand SMSService with common column serviceid:

SELECT sp.SMS,ss.CMD 
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss 
WHERE sp.serviceid=5431 
AND ss.ServiceID = 5431 
AND Receiver ="232700000" 
AND date(TimeStamp) <='2013-08-07' 
AND date(TimeStamp) >='2013-08-06' \G;
Fred Ondieki
  • 2,314
  • 25
  • 23
-1

you can try this works always for me

query="SELECT * from tableX,tableY,table8";