我想在sql中加入三个表,但无法获得所需的结果

时间:2019-01-23 13:03:39

标签: sql

SELECT COUNT(TAB1.ID),
       COUNT(TAB2.ID) Results,
       COUNT(TAB3.ID) Dropout 
  FROM TAB1 INNER JOIN  
       TAB2 on TAB1.ID = TAB2.ID INNER JOIN  
       TAB3 on TAB1.ID = TAB3.ID 
 WHERE TAB1.ID='405'

The answer i expect is 2,3,4 but it returns 24,24,24.

它表示多个条目

3 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-使用不同的计数

SELECT COUNT(distinct TAB1.ID),COUNT(distinct TAB2.ID) Results,COUNT(distinct 
TAB3.ID) Dropout FROM TAB1 
INNER JOIN  TAB2 on TAB1.ID=TAB2.ID 
INNER JOIN  TAB3 on TAB1.ID=TAB3.ID 
WHERE TAB1.ID='405'

答案 1 :(得分:0)

我将切换到相关子查询:

SELECT TAB1.ID, COUNT(TAB1.ID),
       (select COUNT(TAB2.ID) from TAB2 where TAB1.ID=TAB2.ID) Results,
       (select COUNT(TAB3.ID) from TAB3 where TAB1.ID=TAB3.ID) Dropout
FROM TAB1 
WHERE TAB1.ID = '405'  -- to be removed when GROUP BY is added
GROUP BY TAB1.ID  -- more general version

甚至会返回结果或辍学值为零的行。

答案 2 :(得分:0)

我猜测COUNT(DISTINCT)是您想要的。没有样本数据,很难提出更具体的建议:

SELECT COUNT(DISTINCT TAB1.ID), 
       COUNT(DISTINCT TAB2.ID) as Results,
       COUNT(DISTINCT TAB3.ID) as Dropout
FROM TAB1 INNER JOIN
     TAB2 
     ON TAB1.ID = TAB2.ID INNER JOIN
     TAB3 
     ON TAB1.ID = TAB3.ID
WHERE TAB1.ID = '405';  -- Are the single quotes really necessary?