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

roc*_*tas 7 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 |
+------+
Run Code Online (Sandbox Code Playgroud)

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

+-------++------+
| open  || open |
+-------++------+
| 36.99 || 4.27 |
| 36.85 || 4.46 |
| 36.40 || 4.38 |
| 36.33 || 4.22 |
| 36.33 || 4.18 |
+-------++------+
Run Code Online (Sandbox Code Playgroud)

我尝试以下查询:

select a.open, b.open from  table_a a, table_b b;
Run Code Online (Sandbox Code Playgroud)

这将为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 |
+   ... ++------+
Run Code Online (Sandbox Code Playgroud)

我可以看到我在这里误解了别名的正确用法.有任何想法吗?

Tar*_*ryn 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
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo