如何在SQL Server 2012中的某个条件上内联表?

时间:2015-08-10 18:30:07

标签: sql-server

我希望执行的SELECT语句中有一系列连接。 但是,我想只在满足某个条件时才执行最终连接(INNER JOIN)。 该查询通过将逗号分隔的单词串分隔为单词表来创建CTE。我有另一张表,我正在加入此CTE以过滤结果。但是,如果用户没有输入任何字符串,我不想加入此表。有没有办法在INNER JOIN上设置一些条件?

SELECT  dt.Document_ID, 
    dt.Document_NAME, 
    c.Company_ID,
    c.Company_NAME, 
    ct.Category_ID,
    ct.Category_NAME,
    dt.Employee_ID,
    e.First_NAME AS Employee_First_NAME,
    e.Last_NAME AS Employee_Last_NAME,
    p.Project_ID,
    p.Project_NAME,
    dt.Document_DATE,
    dt.Updated_By_ID,
    u.First_NAME AS Updated_First_NAME,
    u.Last_NAME AS Updated_Last_NAME
FROM Documents_T1 AS dt
    LEFT JOIN Companies_T1 AS c ON c.Company_ID=dt.Company_ID
    LEFT JOIN Categories_T1 AS ct ON ct.Category_ID=dt.Category_ID
    LEFT JOIN Users_T1 AS e ON e.User_ID=dt.Employee_ID
    LEFT JOIN Projects_T1 AS p ON p.Project_ID=dt.Project_ID
    LEFT JOIN Users_T1 AS u ON u.User_ID=dt.Updated_By_ID 
    INNER JOIN TagsCTE AS tcte ON tcte.Document_ID=dt.Document_ID

2 个答案:

答案 0 :(得分:1)

不,无论是否在代码中,都会执行INNER JOIN。但是,您可以使用LEFT JOIN并在连接条件中包含 您将使用哪种测试来确定是否应该执行连接。

这样做的结果是,如果条件为真,则根据其余条件执行连接,如果为false,则会为这些行中的连接表返回NULL结果。 / p>

SELECT  dt.Document_ID, 
    dt.Document_NAME, 
    c.Company_ID,
    c.Company_NAME, 
    ct.Category_ID,
    ct.Category_NAME,
    dt.Employee_ID,
    e.First_NAME AS Employee_First_NAME,
    e.Last_NAME AS Employee_Last_NAME,
    p.Project_ID,
    p.Project_NAME,
    dt.Document_DATE,
    dt.Updated_By_ID,
    u.First_NAME AS Updated_First_NAME,
    u.Last_NAME AS Updated_Last_NAME
FROM Documents_T1 AS dt
    LEFT JOIN Companies_T1 AS c ON c.Company_ID=dt.Company_ID
    LEFT JOIN Categories_T1 AS ct ON ct.Category_ID=dt.Category_ID
    LEFT JOIN Users_T1 AS e ON e.User_ID=dt.Employee_ID
    LEFT JOIN Projects_T1 AS p ON p.Project_ID=dt.Project_ID
    LEFT JOIN Users_T1 AS u ON u.User_ID=dt.Updated_By_ID 
    **LEFT** JOIN TagsCTE AS tcte ON tcte.Document_ID=dt.Document_ID AND <<condition>>

答案 1 :(得分:1)

实际上你根本不想加入。您希望将此信息放在where子句中。

SELECT
    dt.Document_ID, 
    dt.Document_NAME, 
    c.Company_ID,
    c.Company_NAME, 
    ct.Category_ID,
    ct.Category_NAME,
    dt.Employee_ID,
    e.First_NAME AS Employee_First_NAME,
    e.Last_NAME AS Employee_Last_NAME,
    p.Project_ID,
    p.Project_NAME,
    dt.Document_DATE,
    dt.Updated_By_ID,
    u.First_NAME AS Updated_First_NAME,
    u.Last_NAME AS Updated_Last_NAME 
FROM Documents_T1 AS dt
    LEFT JOIN Companies_T1 AS c ON c.Company_ID=dt.Company_ID
    LEFT JOIN Categories_T1 AS ct ON ct.Category_ID=dt.Category_ID
    LEFT JOIN Users_T1 AS e ON e.User_ID=dt.Employee_ID
    LEFT JOIN Projects_T1 AS p ON p.Project_ID=dt.Project_ID
    LEFT JOIN Users_T1 AS u ON u.User_ID=dt.Updated_By_ID  
WHERE
    dt.ID IN (SELECT Document_ID FROM TagsCTE)
    OR
    (SELECT TOP 1 ID FROM TagsCTE) IS NULL

简单来说,表D和表T

SELECT * FROM D
WHERE
 D.ID IN (SELECT ID FROM T)
 OR (SELECT TOP 1 ID FROM T) IS NULL