查询 - 使用LEFT,RIGHT,INNER或UNION

时间:2016-03-25 12:17:49

标签: sql join

我有一个包含9个表的数据库,我需要创建一个查看所有表的合适视图。ERD Diragram

我在ERD图左侧的查询对CountyCountryCustomerTypeAssociations工作正常。我也有Accounts的代码(我认为),但是当我开始添加AccountType表时,它无法识别AccountTypeID中的Accounts

所以现在我有两个查询可以工作,但我需要加入这两个查询才能看到创建视图的所有数据。查询1包含与Customer表交互的所有表的所有数据(使用多个连接),Query 2具有与Accounts表交互的所有表的所有数据(使用多个连接)。

查询左侧:

SELECT
    Cus.CustomerId,
    Cus.FirstName,
    Cus.LastName,
    Cty.CountyName,
    Cry.CountryName,
    Cut.CustomerType,
    Ass.AssociationType,
    Ass.CustomerId1,
    Ass.CustomerId2,
    Acc.AccountId
FROM
    Customers Cus
LEFT JOIN
(
SELECT
   Cty.CountyId,
   Cty.CountyName
FROM 
    County Cty
WHERE 
    Cty.IsDeleted = 0) 
AS 
    Cty 
ON 
    Cus.CountyId = Cty.CountyId
LEFT JOIN
(
SELECT
    Cry.CountryId,
    Cry.CountryName
FROM 
    Country Cry
WHERE 
    Cry.IsDeleted = 0) 
AS 
    Cry 
ON 
    Cus.CountryId = Cry.CountryId
LEFT JOIN
(
SELECT
    Cut.CustomerTypeId,
    Cut.CustomerType
FROM 
    CustomerTypes Cut
WHERE 
    Cut.IsDeleted = 0) 
AS 
    Cut 
ON 
    Cus.CustomerTypeId = Cut.CustomerTypeId
LEFT JOIN
(
SELECT
    Ass.AssociationId,
    Ass.AssociationType,
    Ass.CustomerId1,
    Ass.CustomerId2
FROM 
    Associations Ass
WHERE 
    Ass.IsDeleted = 0) 
AS 
    Ass 
ON 
    Cus.AssociationId = Ass.AssociationId
RIGHT JOIN
(
SELECT
    Acc.AccountId,
    Acc.CustomerId
FROM
    Accounts Acc
WHERE 
    Acc.IsDeleted = 0) 
AS 
    Acc 
ON 
    Cus.CustomerId = Acc.CustomerId
WHERE 
    Cus.IsDeleted = 0

右手边的查询。

SELECT
    Acc.AccountId,
    Acc.CustomerId,
    Act.AccountType,
    Tra.TransactionType,
    Sec.SecurityType
FROM
        Accounts Acc
LEFT JOIN
(
SELECT
    Act.AccountTypeId,
        Act.AccountType
FROM
        AccountType Act
WHERE 
    Act.IsDeleted = 0) 
AS 
    Act 
ON 
    Acc.AccountTypeId = Act.AccountTypeId
LEFT JOIN
(
SELECT
    TransactionId,
    TransactionType
FROM 
    Transactions Tra
WHERE 
    Tra.IsDeleted = 0) 
AS 
    Tra 
ON 
    Acc.TransactionId = Tra.TransactionId
RIGHT JOIN
(
SELECT
    SecurityId,
    SecurityType
FROM 
    Securities Sec
WHERE 
    Sec.IsDeleted = 0) 
AS 
    Sec 
ON 
    Acc.SecurityId = Sec.SecurityId
WHERE 
    Acc.IsDeleted = 0

有什么想法吗?谢谢安东尼。

0 个答案:

没有答案
相关问题