创建包含多个表的视图?

时间:2015-04-01 17:52:35

标签: mysql sql database join view

我正在尝试创建一个包含5个表的视图但是在尝试将最后两个表连接在一起时遇到问题。

这是我当前的MySQL查询:

CREATE VIEW s_view AS
    SELECT AC.id, A.id AS account_id, A.name, A.description, A.industry, A.phone_fax, A.phone_office, A.shipping_address_street, A.shipping_address_city, A.shipping_address_state, A.shipping_address_postalcode, A.shipping_address_country, C.id AS contact_id, C.first_name, C.last_name, C.title, C.department, C.phone_home, C.phone_mobile, C.phone_work, C.primary_address_street, C.primary_address_city, C.primary_address_state, C.primary_address_postalcode, C.primary_address_country, EA.Email_address
    FROM ACCOUNTS A
    INNER JOIN ACCOUNTS_CONTACTS AS AC ON A.id = AC.account_id 
    INNER JOIN CONTACTS AS C ON C.id = AC.contact_id 
    INNER JOIN EMAIL_ADDR_BEAN_REL AS ER ON ER.bean_id = A.id
    INNER JOIN EMAIL_ADDRESSES AS EA ON ER.email_address_id = EA.id

我的表格按以下方式设置:

ACCOUNTS(id,first_name,last_name等)

联系人(身份证,姓名等)

ACCOUNT_CONTACTS(id,account_id,contact_id)

EMAIL_ADDR_BEAN_REL(id,bean_id(与account_id / contact_id相同),email_address_id)

EMAIL_ADDRESSES(email_address_id,email_address)

我遇到的问题是EMAIL_ADDR_BEAN_REL表有一个bean_id,可以引用account_id或contact_id。因此,当我加入表格时,它只返回帐户电子邮件地址,但我希望它返回帐户电子邮件地址和联系人电子邮件地址?

我有一种感觉,这是我加入桌面的方式的问题,但我不确定如何前进?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以为EMAIL_ADDR_BEAN_REL表设置2个单独的别名并适当引用它(因为您的结构必须添加另一个别名版本的email_address):

CREATE VIEW s_view AS
    SELECT AC.id, A.id AS account_id, A.name, A.description, A.industry, 
        A.phone_fax, A.phone_office, A.shipping_address_street, 
        A.shipping_address_city, A.shipping_address_state, 
        A.shipping_address_postalcode, A.shipping_address_country, 
        C.id AS contact_id, C.first_name, C.last_name, C.title, 
        C.department, C.phone_home, C.phone_mobile, C.phone_work, 
        C.primary_address_street, C.primary_address_city, 
        C.primary_address_state, C.primary_address_postalcode, 
        C.primary_address_country, 
        EA.Email_address, 
        EA_C.Email_address AS Email_address_c
    FROM ACCOUNTS A
    INNER JOIN ACCOUNTS_CONTACTS AS AC ON A.id = AC.contact_id 
    INNER JOIN CONTACTS AS C ON C.id = AC.account_id 
    LEFT JOIN EMAIL_ADDR_BEAN_REL AS ER ON ER.bean_id = AC.id
        AND ER.bean_module = 'accounts'
    LEFT JOIN EMAIL_ADDR_BEAN_REL AS ER_C ON ER.bean_id = C.id
        AND ER_C.bean_module = 'contacts'
    LEFT JOIN EMAIL_ADDRESSES AS EA ON ER.email_address_id = EA.id
    LEFT JOIN EMAIL_ADDRESSES AS EA_C ON ER_C.email_address_id = EA_C.id

修改

由于您不一定有帐户或联系人的行(如果我从上面的评论中正确理解 - 谢谢,@ BK435),它现在被设置为LEFT JOIN。我还添加了bean_module列的指定(虽然我不确定您使用的是哪种代码)。