编写SELECT查询以将来自一个表的结果组合在另一个表之上

时间:2014-03-14 11:43:27

标签: mysql

我有两个表结构为:

CREATE TABLE tb_first
{
    Name VARCHAR(30),
    Address VARCHAR(30),
    ID INT
};

CREATE TABLE tb_second
{
    Organisation VARCHAR(30),
    Organisation_Address VARCHAR(30),
    Organisation_ID INT
};

我需要运行一个查询,从表tb_first的ID列和表tb_second的Organisation_ID列中选择数据,并将它们放在一个名为Identity的列中。

tb_first:

                        ------------------------------------------------------
                        |      Name   |      Address       |      ID         |
                        ------------------------------------------------------
                        |      John   |  Witham Hall       |      201        |
                        ......................................................
                        |      Harris |  Williams Hall     |      203        |
                        ------------------------------------------------------

tb_second:

                        ------------------------------------------------------
                        |      Name   |      Address       |      ID         |
                        ------------------------------------------------------
                        | Ample Steels| Maureen Brown      |     1201        |
                        ......................................................
                        |John's Sweets| Oklahoma City      |     1203        |
                        ------------------------------------------------------

选择查询必须将结果返回为:

                        ------------------------------------------------------
                        |      Name   |      Address       |   Identity      |
                        ------------------------------------------------------
                        | Ample Steels| Maureen Brown      |     1201        |
                        ......................................................
                        |John's Sweets| Oklahoma City      |     1203        |
                        .....................................................
                        |      John   |  Witham Hall       |      201        |
                        ......................................................
                        |      Harris |  Williams Hall     |      203        |
                        ------------------------------------------------------

3 个答案:

答案 0 :(得分:0)

使用此查询

SELECT Name,Address,ID as Identity FROM tb_first
UNION 
SELECT Organisation,Organisation_address,ID  FROM tb_second

答案 1 :(得分:0)

使用此查询:

select * from tb_first
union all
select * from tb_second;

检查小提琴: http://sqlfiddle.com/#!2/7967d/1

答案 2 :(得分:0)

这个查询在没有union的xampp中工作。试试吧

select * from `tb_first`,`tb_second`