I have 2 tables: table_a and table_b. Both contain a column named 'open'.
table_a
+-------+
| open |
+-------+
| 36.99 |
| 36.85 |
| 36.40 |
| 36.33 |
| 36.33 |
+-------+
table_b
+------+
| open |
+------+
| 4.27 |
| 4.46 |
| 4.38 |
| 4.22 |
| 4.18 |
+------+
I'd like to write a query that returns the following
+-------++------+
| open || open |
+-------++------+
| 36.99 || 4.27 |
| 36.85 || 4.46 |
| 36.40 || 4.38 |
| 36.33 || 4.22 |
| 36.33 || 4.18 |
+-------++------+
I attempt the following query:
select a.open, b.open from table_a a, table_b b;
This returns a table with every value of table_b.open for each value of table_a.open
+-------++------+
| open || open |
+-------++------+
| 36.99 || 4.27 |
| 36.99 || 4.46 |
| 36.99 || 4.38 |
| 36.99 || 4.22 |
| ... || 4.18 |
+ ... ++------+
I can see I'm misunderstanding proper usage of aliases here. Any ideas?
It is not an alias problem that you have. You are performing a CROSS JOIN
on the table which creates a cartesian result set.
This multiplies your result set so every row from table_a
is matched directly to every row in table_b
.
If you want to JOIN
the tables together, then you need some column to join the tables on.
If you have a column to JOIN
on, then your query will be:
select a.open as a_open,
b.open as b_open
from table_a a
inner join table_b b
on a.yourCol = b.yourCol
If you do not have a column that can be used to join on, then you can create a user-defined variable to do this which will create a row number for each row.
select
a.open a_open,
b.open b_open
from
(
select open, a_row
from
(
select open,
@curRow := @curRow + 1 AS a_row
from table_a
cross join (SELECT @curRow := 0) c
) a
) a
inner join
(
select open, b_row
from
(
select open,
@curRow := @curRow + 1 AS b_row
from table_b
cross join (SELECT @curRow := 0) c
) b
) b
on a.a_row = b.b_row;
See SQL Fiddle with Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With