我有一个用于从另一个表中提取数据的连接查询:
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]
如果第3个表值匹配,我需要添加缩小范围的能力:
Where producttheme.productid = variable-paramater-here
AND producttheme.themeid = theme.pk_theme
以下是该表的图片:
因此,如果上面选择了1,它将返回所有[主题]。[名称]和关联的[ThemeType]。[Type]其中ThemeId与ProductId = 1
相关联编辑:更清楚ThemeId是主题表中存在Theme.Name的主键。
答案 0 :(得分: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]
答案 1 :(得分:1)
根据您在添加第3个表之前是否需要WHERE
条件,您可以尝试以下两个选项之一:
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
我希望这能为你提供一些工作。
如果您提供一些示例数据,我可以设置一个工作示例。