在三个表上使用union命令(mysql)

时间:2016-02-29 09:23:25

标签: mysql union

我有以下内容:

tblOwner: owner_num,lname,fname (PK owner_num)
tblMarina_slip: owner_num, slip_id (PK slip_id, FK owner_num)
tblService_Requests: service_id, slip_id, description (PK service_id, FK slip_id)

我是MySql的新手,需要使用Union命令来获取

的输出
tblOwner.Owner_num, tblOwner.Lname, tblOwner.Fname, tblServiceRequests.service_id, tblServiceRequests.Description

我不知道如何使用" union"命令获取所需的数据集,当这三个表之间的唯一连接是tblMarina_slip和tblService_Requests中的外键时。

3 个答案:

答案 0 :(得分:0)

你需要一个联盟而不是一个联盟:

SELECT t.owner_num,t.Lname,t.Fname,s.service_id,s.description
FROM tblOwner t 
INNER JOIN tblMarina_slip p on(t.owner_num = p.owner_num)
INNER JOIN tblService_Requests s on(p.slip_id = s.slip_id)

union用于将两个或多个输出组合在一起(仅在它们与列号和列类型相同的情况下)

当你想在同一行显示多个表信息时,你应该像我的答案一样使用JOIN。

修改

如果您需要使用union,您可以像这样欺骗数据:

SELECT max(owner_num),max(Lname),max(Fname),slip_id,max(description)
FROM
    (SELECT owner_num,max(Lname) as Lname,max(Fname) as Fname, max(slip_id) as slip_id,'' as description
    FROM(
        SELECT owner_num,Lname,Fname,0 as slip_id from tblOwner
        UNION
        SELECT owner_num,'' as Lname,'' as Fname,slip_id from tblMarina_slip)
    GROUP BY owner_num
    UNION
    SELECT 0 as owner_num, '' as Lname, '' as Fname,slip_id,description FROM tblService_Requests)
GROUP BY slip_id

答案 1 :(得分:0)

您不需要联合命令:

select  tow.Owner_num, tow.Lname, tow.Fname, ts.service_id, ts.Description
  from  tblOwner tow, tblServiceRequests ts, tblMarina_slip tm
 where  tow.owner_num = tm.owner_num
   and  tm.slip_id    = ts.slip_id

答案 2 :(得分:-1)

select col1,col2,col3 from <tablename> where <conditions> 
union
    select col1,col2,col3 from <tablename> where <conditions> 
union
    select col1,col2,col3 from <tablename> where <conditions>

注意:每个表中的col1col2col3必须相同。