如何在MySql中连接两个表时创建视图

时间:2013-10-26 21:52:34

标签: mysql join view

我需要创建一个名为customer_addresses的视图,其中显示每个客户的送货地址和帐单地址。此视图应从Customers表中返回这些列:

customer_id  
email_address  
last_name  
first_name.

此视图应从地址表中返回这些列:

bill_line1  
bill_line2  
bill_city  
bill_state  
bill_zip  
ship_line1  
ship_line2  
ship_city  
ship_state  
ship_zip  

此视图中的行应按last_name和first_name列进行排序。

备注
customers表包括以下列:customer_id,email_address,password,first_name,last_name,shipping_address_id和billing_address_id

地址表包括以下列:address_id,customer_id,line1,line2,city,state,zip_code,phone

我试图发布两张桌子的图片,但我在这里是全新的,还没有10个代表。由于billing_id / shipping_id已转换为实际地址,我主要在加入声明中遇到问题。

1 个答案:

答案 0 :(得分:0)

加入“地址”表两次,将一个链接到帐单邮寄地址ID,另一个链接到送货地址ID。

CREATE VIEW CUSTOMER_ADDRESSES AS 
SELECT cust.customer_id, cust.last_name, cust.first_name, cust.email_address
bill.line1 as bill_line1, bill.line2 as bill_line2, bill.city as bill_city, 
bill.state as bill_state, bill.zip as bill_zip, 
ship.line1 as ship_line1, ship.line2 as ship_line2, ship.city as ship_city, 
ship.state as ship_state, ship.zip as ship_zip 
FROM customers cust, addresses bill, addresses ship 
WHERE cust.shipping_address_id = ship.address_id 
and cust.billing_address_id = bill.address_id