22

The result of a query I need to create will only return a single row. The data I need to pull comes from two tables without any relational columns. The second table only has additional rows added once per year so I'll construct the query via PHP as necessary.

I know how to use SQL sub-SELECTs however I'm not sure how to SELECT multiple columns FROM a second table when there is no relational data in a performance oriented/dynamic way.

Here is a static example where I use multiple sub-SELECTs to visualize what I'm trying to do...

SELECT t1.a, 
t1.b, 
t1.c, 
(SELECT t2.d FROM table2) AS d, 
(SELECT t2.e FROM table2) AS e, 
(SELECT t2.f FROM table2) AS f, 
(SELECT t2.g FROM table2) AS g, 
t1.h, 
t1.i
FROM table1 AS t1;

How do I dynamically and efficiently pull multiple columns from a second table that has no relational columns with the first table?

I do not want to create a second separate query as it would be cheap solution, most likely have some impact on performance and worst of all I wouldn't expand my understanding of SQL.

2 Answers 2

31

Sounds like you need a cartesian join (no join) -- but you WILL multiply the values together (ie, if table 1 has 100 rows and table 2 has 10 rows, you'll return 1000 rows)

SELECT t1.a, 
t1.b, 
t1.c, 
t2.d, 
t2.e, 
t2.f,
t2.g,
t1.h, 
t1.i
FROM table1 AS t1, table2 as t2;
Sign up to request clarification or add additional context in comments.

2 Comments

how do you do this in Ruby on Rails?
I'm no ROR expert, but it's basically querying from 2 tables without joining them. Do you have an example of a "select * from blah" type query in ROR?
8

The syntax to do so is:

SELECT t1.a, 
       t1.b, 
       t1.c, 
       t2.d, 
       t2.e, 
       t2.f, 
       t2.g, 
       t1.h, 
       t1.i
FROM table1 AS t1, table2 as t2;

If you're not joining the two tables though, you'll usually want two queries. Else, you'll get a cartesian product of the two tables:

http://en.wikipedia.org/wiki/Cartesian_product

2 Comments

same answer as I posted.
@JoeLove: Answered at very much the same time. If you're the one who down voted, you might want to check this out for future reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.