【发布时间】:2020-02-20 13:50:13
【问题描述】:
我正在处理我的 C# 项目,由于 .sql 过程,我必须从数据库中获取数据。
合成:
表 ProprietesCourantes 链接到表 Entite。
表 Archive 链接到表 EntiteArchive
==> 我想在ProprietesCourantes 和Archive 之间建立一个链接,感谢字段Libellé
表ProprietesCourantes
我有几张桌子:
SELECT TOP (1000) [IdEntite]
,[Libelle]
,[EstActif]
, ...
, ...
FROM [Database].[dbo].[ProprietesCourantes]
WHERE [Libelle] = 'DELTA SERVICE AUTO';
表Entite
SELECT TOP (1000) [IdEntite]
,[TypeEntite]
,[CodeEntite]
,[TypeCodeEntite]
FROM [Database].[dbo].[Entite]
WHERE IdEntite = '165';
表Archive
SELECT TOP (1000) [IdArchive]
,[IdEntite]
,[NoteFinale]
,[EstValide]
FROM [Database].[dbo].[Archive]
WHERE IdEntite = '33' and EstValide = '1';
表EntiteArchive
SELECT TOP (1000) [IdEntite]
,[TypeEntite]
,[CodeEntite]
,[Libelle]
,...
FROM [Database].[dbo].[EntiteArchive]
我的 SQL 请求:
SELECT
ProprietesCourantes.IdEntite as IdEntite,
ProprietesCourantes.Libelle as RaisonSociale,
Entite.CodeEntite as IdCMCIC,
ProprietesCourantes.NomParent as NomGN,
Archive.NoteFinale as Cotation,
Archive.DateValiditeQuestionnaireDeSoutien as DateValiditeQuestionnaireDeSoutien,
ProprietesCourantes.CodePays as Pays,
ProprietesCourantes.EstActif as Statut,
CAST(CASE WHEN Entite.CodeEntite = ProprietesCourantes.IdSocMere THEN 1 ELSE 0 END AS BIT) as EstMaisonMere,
ProprietesCourantes.IdCMCICParent as IdCMCICParent,
ProprietesCourantesGN.CodeAlgo as CodeAlgoParent
FROM ProprietesCourantes
LEFT JOIN Archive ON (Archive.IdEntite = ProprietesCourantes.IdEntite and Archive.EstValide=1)
LEFT JOIN Entite ON Entite.IdEntite = ProprietesCourantes.IdEntite
LEFT JOIN Entite as EntiteGN ON EntiteGN.CodeEntite = ProprietesCourantes.IdCMCICParent
LEFT JOIN ProprietesCourantes as ProprietesCourantesGN ON ProprietesCourantesGN.IdEntite = EntiteGN.IdEntite
WHERE Entite.TypeEntite = 1
AND (ProprietesCourantes.Libelle LIKE '%'+'DELTA SERVICE'+'%' )
如您所见:Cotation 和 DateValiditeQuestionnaireDeSoutien 为 NULL,因为 LEFT JOIN Archive ON (Archive.IdEntite = ProprietesCourantes.IdEntite 无法工作(不同的 IDEntite)。
我试图用这个替换,但它不起作用,知道吗?
LEFT JOIN Archive ON ((select EntiteArchive.Libelle from EntiteArchive LEFT JOIN Archive ON (EntiteArchive.IdEntite = Archive.IdEntite)) = ProprietesCourantes.Libelle and Archive.EstValide=1)
【问题讨论】:
-
entite的条件应该在on子句中,而不是where子句中。 -
@GordonLinoff 你能写一个例子来说明你的句子吗?
-
换句话说,通过在左连接表的 WHERE 子句中填充条件,您可以在连接发生后将其应用于整个结果集。本质上,您将
LEFT OUTER JOIN变成INNER JOIN。相反,您希望该过滤器在连接之前发生在您的entite表中,因此子查询或仅将条件移动到ON子句就足够了。 -
@philipxy 不,不是这个问题。我知道我必须写一个简洁的问题,清楚。但就我而言,如果不设置上下文和表格,就不可能解释我的问题以及我想要得到的东西。对不起
标签: sql sql-server tsql left-join where-clause