Noah Martin
Noah Martin

Reputation: 1809

Select columns as select statement from other tables?

I want to retrieve some information through a single sql statement through different tables. I want to do something like:

select col1,
       col2,
       (select col1 
          from table 2),
       (select col1 
          from table 3), 
  from table1 
  join table2 
  join table3

Can anyone help please?

Upvotes: 1

Views: 103

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

First, decide how you want to get the data. If you want to use sub-queries, fine, otherwise use joins. For example, with sub-queries it might look like this:

select t1.col1,
    t1.col2,
    (select col1 from table2 t2 where t2.field = t1.field),
    (select col1 from table3 t3 where t3.field = t1.field)
from table1 t1

In contrast, if you wanted to use joins, it might look like this:

select t1.col1,
    t1.col2,
    t2.col1,
    t3.col1
from table1 t1
    join table2 t2 on t2.field = t1.field
    join table3 t3 on t3.field = t1.field

Upvotes: 2

Hogan
Hogan

Reputation: 70513

select table1.col1 as t1c1, table1.col2 as t1c2, table2.col1 as t2c1, table3.col1 as t3c1
from table1 
join table2 
join table3

note you will need to actually join table2 and table3... join statements like this won't work they don't have the ON part.

Upvotes: 2

Related Questions