sql-server – 如何在SQL Server 2012中的某个条件下INNER JOIN表?

我在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

最佳答案 实际上你根本不需要加入.您希望将此信息放在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
点赞