Sql 一种带过滤的交叉连接查询
我有以下三个表格: dbo.Product Id | Name 1 | P1 2 | P2 dbo.ProductTranslations Id | LangId | Text 1 | 1 | Text_EN 1 | 2 | Text_DE 2 | 1 | OtherText_EN dbo.Language Id | Culture 1 | en-US 2 | de-DE 3 | es-ES dbo.产品 Id |名称 1 | P1 2 | P2 dbo.ProductTranslations Id | LangId |文本 1 | 1 |文本| 1 | 2 |文本| 2 | 1 |其他文本| dbo.语言 Id |文化 1 | en US 2 | de 3 | es 我需要一个类似以下的查询: select * from ProductTranslations pt (some join) Language lang 选择* 来自ProductTranslations pt(一些连接)语言lang 制作: 对于产品1: 1 | en-US | Text_EN 1 | de-DE | Text_DE 1 | es-ES | null 1 | en US | Text | en 1 | de | Text | de 1 | es | null 对于产品2: 2 | en-US | OtherText_EN 2 | de-DE | null 2 | es-ES | null 2 | en US |其他文本| en 2 | de | null 2 | es | null 理想情况下,我希望有一个视图,我可以使用Id进行过滤。 任何帮助都将不胜感激Sql 一种带过滤的交叉连接查询,sql,sql-server,join,jointable,Sql,Sql Server,Join,Jointable,我有以下三个表格: dbo.Product Id | Name 1 | P1 2 | P2 dbo.ProductTranslations Id | LangId | Text 1 | 1 | Text_EN 1 | 2 | Text_DE 2 | 1 | OtherText_EN dbo.Language Id | Culture 1 | en-US 2 | de-DE 3 | es-ES dbo.
SELECT
p.Id
,p.Name
,l.Id as LangId
,l.Culture
,t.Text
FROM
dbo.Product p
CROSS JOIN dbo.Language l
LEFT JOIN dbo.ProductTransalations t
ON p.Id = t.Id
AND l.Id = t.LangId
在产品和语言之间使用笛卡尔连接,以获得它们的所有可能组合,然后左连接ProductTranslations
下面是一个完整的工作示例
DECLARE @Product AS TABLE (Id INT, Name CHAR(2))
DECLARE @ProductTransalations AS TABLE (Id INT, LangId INT, Text VARCHAR(50))
DECLARE @Language AS TABLE (Id INT, Culture VARCHAR(20))
INSERT INTO @Product VALUES (1,'P1'),(2,'P2')
INSERT INTO @ProductTransalations VALUES (1,1,'Text_EN'),(1,2,'Text_DE'),(2,1,'OtherText_EN')
INSERT INTO @Language VALUES (1,'en-US'),(2,'de-DE'),(3,'es-ES')
SELECT
p.Id
,p.Name
,l.Id as LangId
,l.Culture
,t.Text
FROM
@Product p
CROSS JOIN @Language l
LEFT JOIN @ProductTransalations t
ON p.Id = t.Id
AND l.Id = t.LangId
我明白了。您需要所有语言的行,即使没有匹配的翻译 您可以使用
左连接来执行此操作
:
select p.productId, l.culture, pt.text
from (select 1 as productId) p cross join
language l left join
ProductTranslations pt
on pt.id = p.productId and pt.langid = l.id;
你可以把“1”改成你喜欢的任何产品
如果您喜欢使用where
子句,可以执行以下操作:
select p.productId, l.culture, pt.text
from product p cross join
language l left join
ProductTranslations pt
on pt.id = p.productId and pt.langid = l.id
where p.id = 1;
提示:
JOIN
就足够了。