简体   繁体   中英

How to create a view while joining two tables in MySql

I need to Create a view named customer_addresses that shows the shipping and billing addresses for each customer. This view should return these columns from the Customers table:

customer_id  
email_address  
last_name  
first_name.

This view should return these columns from the Addresses table:

bill_line1  
bill_line2  
bill_city  
bill_state  
bill_zip  
ship_line1  
ship_line2  
ship_city  
ship_state  
ship_zip  

The rows in this view should be sorted by the last_name and then first_name columns.

Notes
The customers table includes the following columns: customer_id, email_address, password, first_name, last_name, shipping_address_id, and billing_address_id

The Addresses table includes the following columns: address_id, customer_id, line1, line2, city, state, zip_code, phone

I tried to post a picture of both tables but I am brand new here and do not yet have 10 rep. I am primarily having issues within the join statement due to the conversion of billing_id / shipping_id to actual addresses.

Join the 'addresses' table twice, linking one to the billing address id, and the other to shipping address 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM