8

我有 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 |
+   ... ++------+

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

4

2 回答 2

7

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

这会使您的结果集成倍增加,因此 fromtable_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

于 2013-03-03T20:54:51.357 回答
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
于 2013-03-03T20:59:10.880 回答