且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 19:31:16

这不是别名问题。您正在执行 交叉加入 在创建笛卡尔结果集的表格上。

It is not an alias problem that you have. You are performing a CROSS JOIN on the table which creates a cartesian result set.

这会乘以结果集,因此 table_a 中的每一行都直接与 table_b

This multiplies your result set so every row from table_a is matched directly to every row in table_b.

如果您想一起 JOIN 个表,则需要一些列来连接表格。

If you want to JOIN the tables together, then you need some column to join the tables on.

如果您有要加入 JOIN 的列,则查询将为:

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;

请参见带有演示的SQL提琴