数据库合并表

时间:2012-02-23 03:30:03

标签: mysql database merge

我只想问一下如何合并两个表。

因为我有一个餐桌客人和公司,他们都获得了预订。

我想加入他们两个并将其标记为客户,我想添加一个新的列客户类型,如果我的公司为空,则会说客人...和公司,如果我的客人为空... < / p>

以下是一个例子:

guest(g_id(PK), name, guest details etc....)
company(c_id(PK), name, company details etc...)
reservation(r_id(PK), g_id(fk), c_id(fk), reservation details etc...)

当我加入他们时(假设客人已获得预订),我的表格似乎是

reservation_id|company name|guest name|reservation details
     1           null      <name>     <details>
     2           null      <name>     <details>

我想要的是这样:

reservation_id|customer name|cust_type|reservation details
     1          <name>      <guest>     <details>
     2          <name>      <company>     <details>

2 个答案:

答案 0 :(得分:2)

一种可能的解决方案是首先为每种类型的预留(您可能已经拥有)创建一个查询,然后在那里添加cust_type,然后将两者结合在一起。因此,初始查询将类似于:

guest_reservations:

SELECT reservation.r_id, guest.name, "guest" AS cust_type, {other fields}
FROM guest, reservation INNER JOIN guest ON guest.g_id = reservation.g_id;

company_reservations:

SELECT reservation.r_id, company.name, "company" AS cust_type {other fields}
FROM company, reservation INNER JOIN company ON company.c_id = reservation.c_id;

然后你可以将两个查询结合在一起,如下所示。

SELECT reservation.r_id, guest.name, "guest" AS cust_type, {other fields}
FROM guest, reservation INNER JOIN guest ON guest.g_id = reservation.g_id
UNION SELECT reservation.r_id, company.name, "company" AS cust_type {other fields}
FROM company, reservation INNER JOIN company ON company.c_id = reservation.c_id;

当然记得要么删除{其他字段},要么添加你需要的其他内容。

答案 1 :(得分:2)

不确定架构是否最佳,但请考虑以下表格:

Res(resId,description,cid,gid,details)

1   Guest Res   1   NULL    Just some guy
2   Comp Res    NULL    1   Corporate jerk

嘉宾(gid,姓名)

1   Chuck

公司(cid,名称)

1   Tenth

查看选择查询的参数:

1. r.rid : id of reservation table
2. isnull(c.name, g.name) : gets the non null value from either company or guest
3. isnull(replace(c.name, c.name, 'Company'), 'Guest') as type
    Fanciness...if c.name is something, then 'Company', otherwise 'Guest'
4. r.details : reservation details

由于空值,您需要外连接,这为您提供了数据的完整视图。

left outer join company c on r.cid = c.cid
left outer join guest g on r.gid = g.gid

所以,如果你把它们全部放在一起就可以得到你想要的东西:

select r.rid, r.description, isnull(c.name, g.name), 
isnull(replace(c.name, c.name, 'Company'), 'Guest') as type, 
r.details from res r
left outer join company c on r.cid = c.cid
left outer join guest g on r.gid = g.gid

1   Guest Res   Chuck   Guest   Just some guy
2   Comp Res    Tenth   Company Corporate jerk