在我的数据库中,我有9个表,我需要创建一个视图。
此视图最终将查询所有表。这里的一个一致性是IsDeleted的所有表中都有一列。如何运行查询以检查IsDeleted = 0的所有表中的列?
这三个表是:客户,县,国家
这是我的观点:
CREATE VIEW vwTEST
AS
SELECT
Cus.CustomerId,
Cus.FirstName,
Cus.LastName,
Cty.CountyName,
Cry.CountryName
FROM
Customers Cus
LEFT JOIN
County Cty
ON
Cus.CountyId = Cty.CountyId
WHERE
Cus.IsDeleted = 0
LEFT JOIN
Country Cry
ON
Cus.CountryId = Cry.CountryId
WHERE
Cry.IsDeleted = 0
答案 0 :(得分:1)
问题是当你在外部(即LEFT
)加入一个表但在WHERE
子句中对该表有条件时,你实际上将连接转换为内部加入。这是因为在之后执行where子句条件然后执行了离子,但是错过的连接对于它们的列都具有所有空值,因此任何比较都将失败。
解决方案是将外连接表上的所有条件移动到连接的ON
子句中,该子句在连接时执行
CREATE VIEW vwTEST AS
SELECT
Cus.CustomerId,
Cus.FirstName,
Cus.LastName,
Cty.CountyName,
Cry.CountryName
FROM Customers Cus
LEFT JOIN County Cty
ON Cus.CountyId = Cty.CountyId
AND Cus.IsDeleted = 0
LEFT JOIN Country Cry
ON Cus.CountryId = Cry.CountryId
AND Cry.IsDeleted = 0
当只有已删除的行可用时,此查询仍允许县和国家/地区不加入。
看起来你本能地知道这一点,但我不知道表达它的语法,因为我所要做的就是将WHERE
更改为AND
。
答案 1 :(得分:0)
这取决于你想要的结果。如果您还想要那些未删除但删除了县或国家/地区的客户,则必须创建子查询以仅选择未删除的记录并加入:
CREATE VIEW vwTEST
AS
SELECT
Cus.CustomerId,
Cus.FirstName,
Cus.LastName,
Cty.CountyName,
Cry.CountryName
FROM
Customers Cus
LEFT JOIN
(SELECT
County.CountyId,
County.CountyName
FROM County
WHERE County.IsDeleted = 0) AS Cty ON Cus.CountyId = Cty.CountyId
LEFT JOIN
(SELECT
Country.CountryId,
Country.CountryName
FROM Country
WHERE Country.IsDeleted = 0) AS Cry ON Cus.CountryId = Cry.CountryId
WHERE Cus.IsDeleted = 0;
结果(此处包含所有字段)将为:
如果您只想要没有删除任何内容的行,那么它只是:
SELECT
*
FROM Customers Cus
LEFT JOIN County Cty ON Cus.CountyId = Cty.CountyId
LEFT JOIN Country Cry ON Cus.CountryId = Cry.CountryId
WHERE Cus.IsDeleted = 0 AND Cty.IsDeleted = 0 AND Cry.IsDeleted = 0;
,结果将是:
我的测试数据集,作为JOIN的结果,没有任何WHERE条件:
SELECT
*
FROM Customers Cus
LEFT JOIN County Cty ON Cus.CountyId = Cty.CountyId
LEFT JOIN Country Cry ON Cus.CountryId = Cry.CountryId;
是:
此致