SQL Server 当ID被多次使用时,我们如何计算来自多个连接的记录?

uxh89sit  于 2022-11-28  发布在  其他
关注(0)|答案(2)|浏览(138)

我尝试从多个表中获取记录计数,如下所示。

Select count(*)
From
(
Select  Hist.Common_Name,
        Veg.ID,
        EDSH.ID
From Hist_Event_View as Hist
Inner Join Vegtables as Veg
ON Hist.Common_Name = Veg.ID
INNER JOIN Final as Final
ON Hist.Common_Name = Final.ID) as Sub

问题是ID被多次使用,所以SQL Server无法在外部查询中解析哪个ID来自哪个表。我该如何处理这个问题?谢谢。

r3i60tvu

r3i60tvu1#

您的假设是正确的,重复的ID是问题所在。您可以通过在子查询中为ID指定别名来处理此问题:

Select count(*)
From
(
Select  Hist.Common_Name,
        Veg.ID as Veg_ID,
        EDSH.ID as EDSH_ID
From Hist_Event_View as Hist
Inner Join Vegtables as Veg
ON Hist.Common_Name = Veg.ID
INNER JOIN Final as Final
ON Hist.Common_Name = Final.ID) as Sub
khbbv19g

khbbv19g2#

我认为可以通过使用别名https://www.w3schools.com/sql/sql_alias.asp来解决此问题
但是为什么需要外部选择呢?为什么不直接写:

Select  count(*)
From Hist_Event_View as Hist
Inner Join Vegtables as Veg
ON Hist.Common_Name = Veg.ID
INNER JOIN Final as Final
ON Hist.Common_Name = Final.ID

相关问题