0

我有一个连接查询,用于从另一个表中提取数据:

SELECT [THEME].[NAME], 
       [THEMETYPE].[TYPE] 
FROM   [THEME] 
       LEFT OUTER JOIN [THEMETYPE] 
                    ON [THEME].[THEMETYPEID] = [THEMETYPE].[PK_THEMETYPE] 
WHERE  COALESCE([THEME].[THEMETYPEID], 'null') LIKE '%' 
ORDER  BY CASE 
            WHEN [THEMETYPE].[TYPE] IS NULL THEN 1 
            ELSE 0 
          END, 
          [THEMETYPE].[TYPE] 

如果第三个表值匹配,我需要添加缩小范围的功能:

Where producttheme.productid = variable-paramater-here 
AND producttheme.themeid = theme.pk_theme 

这是一张桌子的照片:

在此处输入图像描述

因此,如果上面选择了 1,它将返回所有 [Theme].[Name] 和关联的 [ThemeType].[Type],其中 ThemeId 与 ProductId = 1 关联

编辑:更清楚 ThemeId 是 Theme.Name 所在的 Theme 表中的主键。

4

2 回答 2

3

这会给你一些想法,请相应地调整列名:

SELECT [Theme].[Name], [ThemeType].[Type] 
FROM [Theme] 
Left Outer Join [ThemeType] 
ON [Theme].[ThemeTypeId] = [ThemeType].[PK_ThemeType]
join ProductTheme PT
on  PT.ProductID=ThemeType.ProductID
WHERE ProductTheme.ProductID = VARIABLE-PARAMATER-HERE AND ProductTheme.ThemeId = Theme.PK_Theme
ORDER BY [ThemeType].[Type]
于 2013-07-29T14:55:20.197 回答
1

根据在添加第三张表之前是否需要WHERE条件,您可以尝试以下 2 个选项之一:

SELECT * 
FROM   TABLE1 T1 
       LEFT OUTER JOIN TABLE2 T2 
                    ON T1.FIELDA = T2.FIELDA 
       INNER JOIN TABLE3 T3 
               ON T1.FIELDA = T3.FIELDA 
WHERE  T1.FIELDB = 'aaa' 
       AND T3.FIELDC = 12 

或者:

SELECT * 
FROM   (SELECT T1.FIELDA, 
               T2.FIELDB 
        FROM   TABLE1 T1 
               LEFT OUTER JOIN TABLE2 T2 
                            ON T1.FIELDA = T2.FIELDA 
        WHERE  T1.FIELDC = 'aaa')T3 
       INNER JOIN TABLE3 T4 
               ON T3.FIELDA = T3.FIELDA 
                  AND T4.FIELDC = 12 

我希望这能给你一些工作。

如果您提供一些示例数据,我可以设置一个工作示例。

于 2013-07-29T14:53:38.907 回答