如何使用另一个表中的多个列替换表中的一列

时间:2011-08-07 17:16:23

标签: mysql sql

我有一个表有两个不同的地址表引用。我想用视图中的实际列替换每个引用ID。我想象下面的内容,但这不起作用。我正在使用MySQL 5.5。什么是正确的语法?

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;

1 个答案:

答案 0 :(得分:2)

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

如果这些地址引用可能为空,则可以使用LEFT JOIN而不是INNER JOIN。