使用mysql别名从2个表中选择列

时间:2013-03-03 20:50:30

标签: mysql sql select alias

我有2个表:table_a和table_b。两者都包含一个名为“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 |
+------+

我想编写一个返回以下内容的查询

+-------++------+
| open  || open |
+-------++------+
| 36.99 || 4.27 |
| 36.85 || 4.46 |
| 36.40 || 4.38 |
| 36.33 || 4.22 |
| 36.33 || 4.18 |
+-------++------+

我尝试以下查询:

select a.open, b.open from  table_a a, table_b b;

这将为table_a.open的每个值返回一个table_b.open的每个值的表

+-------++------+
| open  || open |
+-------++------+
| 36.99 || 4.27 |
| 36.99 || 4.46 |
| 36.99 || 4.38 |
| 36.99 || 4.22 |
|   ... || 4.18 |
+   ... ++------+

我可以看到我在这里误解了别名的正确用法。有什么想法吗?

2 个答案:

答案 0 :(得分:6)

这不是你的别名问题。您正在表格上执行CROSS JOIN,以创建笛卡尔结果集。

这会使您的结果集倍增,因此table_a的每一行都会直接与table_b中的每一行匹配。

如果你想将JOIN表放在一起,那么你需要一些列来加入表。

如果您有JOIN列,则您的查询将是:

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

如果您没有可用于加入的列,则可以创建用户定义的变量来执行此操作,这将为每行创建行号。

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;

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

您需要一个可用于连接这两个表的列。

您可以尝试将伪列生成为行号,但我不确定这是您要实现的目标。这看起来应该是这样(可以立即测试,但想法很明确):

SELECT
    a.open, b.open
FROM
    (SELECT
        open, @curRow := @curRow + 1 AS row_number
     FROM
        table_a
     JOIN
        (SELECT @curRow := 0)
    ) a
JOIN
    (SELECT
        open, @curRow := @curRow + 1 AS row_number
     FROM
        table_b
     JOIN
        (SELECT @curRow := 0)
    ) b
ON
    a.row_number = b.row_number