Steve
Steve

Reputation: 1577

How do I replace one column in a table with multiple columns from another table

I have a table that has two different references to an address table. I would like to replace each reference id with the actual columns in a view. I envision something like what follows, but that does not work. I am using MySQL 5.5. What is the correct grammar?

CREATE VIEW Company AS
select id, Name AccountName, JoinDate, AccountStatus, CompanyName,
( select street1 MailStreet1, street2 MailStreet2, city MailCity, state MailState, county MailCounty, country MailCountry, postalcode MailPostalCode from Addresses where id = MailAddress limit 1 ) ,
( select street1 BillingStreet1, street2 BillingStreet2, city BillingsCity, state BillingState, county BillingCounty, country BillingCountry, postalcode BillingPostalCode from Addresses where id = BillingAddress limit 1 )
from Customer;

Upvotes: 1

Views: 189

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

select 
  c.id, c.Name as AccountName, c.JoinDate, c.AccountStatus, c.CompanyName,
  ma.street1 as MailStreet1, ma.street2 as MailStreet2, ma.city as MailCity, ma state as MailState,
  ma.county as MailCounty, ma.country as MailCountry, ma.postalcode MailPostalCode,
  ba.street1 as MailStreet1, ba.street2 as MailStreet2, ba.city as MailCity, ba state as MailState,
  ba.county as MailCounty, ba.country as MailCountry, ba.postalcode MailPostalCode,
from
  Customer c
  inner join Address ma on ma.id = c.MailAddress
  inner join Address ba on ba.id = c.BillingAddress

You can use LEFT JOIN instead of INNER JOIN if these address references may be empty.

Upvotes: 2

Related Questions