开发者

find the output mysql query

I have a table name T1 having only one Column name Col1 having rows –

Col1
a
b
c

And another table name T2 also having only one Column name Col1 开发者_运维知识库having rows –

Col1
x
y
z

Now I want record like

Col1--Col2
a------x
b------y
c------z

I am using mysql. Thanks in advance!!


create table T1(col1 varchar(10));
insert T1 values ('a'),('b'),('c');
create table T2(col2 varchar(10));
insert T2 values ('x'),('y'),('z');

select A.col1, B.col2 from
(select @r:=@r+1 rownum, col1 from (select @r:=0) initvar, T1) A,
(select @s:=@s+1 rownum, col2 from (select @s:=0) initvar, T2) B
where A.rownum=B.rownum

Because there is no ORDER BY clause, you are depending on luck and convention for the row numbering to be according to the order inserted. It may not always be the case.


In your example, if you want to join the tables to get row results like this:

  • Row 1 - A,X
  • Row 2 - B,Y
  • Row 3 - C,Z

..then you will have to add a common field that you can JOIN the two tables on.

If you want to be able to return results from both tables like this:

  • Row 1 - A
  • Row 2 - B
  • Row 3 - C
  • Row 4 - X
  • Row 5 - Y
  • Row 6 - Z

.. then you will need to use a UNION:

(SELECT Col1 FROM T1) UNION (SELECT Col1 FROM T2)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜