首页 > 解决方案 > How to union four tables in mysql where there is nothing common among them

问题描述

I have four tables where there is nothing common among them.My four tables have few columns they are:

Table 1: EpId,Name,Position,Email,ManagerId,To/From
Table 2: Type
Table 3: LocId,LocName
Table 4: PreName

The expected output is

EpId Name Position email managerId To/From Type LocId LocName PreName 

The query so far is :

(select u.EpId as id,u.Name as Name,
u.Position as Position,u.ManagerId as ManagerId,u.Email as Email 
from Employee as u)
union
(select c.Type as Type from EpType as c)
union
(select l.LocId as LocId,l.LocName as LocName from Location)
union
(select p.Name as PreName from Premise)

But it throws error : The used SELECT statements have a different number of columns

标签: mysql

解决方案


use cross join, but seems you just want to get 1 for each other tables, you use limit

select distinct t1.EpId, t1.Position, t1.email, t1.managerId, t2.Type, t3.LocId , t3.LocName , t4.PreName from 
Employee t1
cross join (select Type as Type from EpType limit 1)t2
cross join (select LocId as LocId,LocName as LocName from Location limit 1) t3
cross join (select Name as PreName from Premise  limit 1) t4

推荐阅读