我有3个表,我加入以获取我想要的数据,company_details,officer_details和company_officer加入这两个。我现在的询问是指那些为超过2家公司工作并且没有辞职的人员。
我想添加到此查询中以仅获取具有多于1个工作者的公司(在应用所有先前的要求之后)。小号
Company_Details
Officer_Details
SELECT
CD.Company_ID,
CD.Company_Name,
CD.Company_Index,
OD.Officer_ID,
OD.Officer_Name,
CO.Officer_Role
FROM
Company_Details CD
INNER JOIN Company_Officer CO
ON CD.Company_ID = CO.Company_ID
INNER JOIN Officer_Details OD
ON CO.Officer_ID = OD.Officer_ID
WHERE CD.Company_Index<>'' AND
CO.Resigned_On='' AND
CO.Officer_ID IN
( SELECT CO2.officer_id
FROM Company_Officer CO2
INNER JOIN Company_Details CD2
ON CO2.Company_ID = CD2.Company_ID
WHERE CO2.Resigned_On='' AND CD2.Company_Index<>''
GROUP BY CO2.officer_id
HAVING Count( DISTINCT CO2.company_id ) > 1
)
ORDER BY `CD`.`Company_Name` ASC, `CD`.`Company_ID` ASC;
在下图中,您可以看到我当前查询的结果。突出显示的2行我想省略,因为你可以看到这些公司只有一名员工,而我想摆脱只有一名员工的选择公司。
答案 0 :(得分:2)
只需在Where子句中添加另一个谓词
SELECT CD.Company_ID, CD.Company_Name, CD.Company_Index,
OD.Officer_ID, OD.Officer_Name, CO.Officer_Role
FROM Company_Details CD
JOIN Company_Officer CO
ON CD.Company_ID = CO.Company_ID
JOIN Officer_Details OD
ON CO.Officer_ID = OD.Officer_ID
WHERE CD.Company_Index<>''
AND CO.Resigned_On=''
AND CO.Officer_ID IN
( SELECT CO2.officer_id
FROM Company_Officer CO2
JOIN Company_Details CD2
ON CO2.Company_ID = CD2.Company_ID
WHERE CO2.Resigned_On='' AND CD2.Company_Index<>''
GROUP BY CO2.officer_id
HAVING Count( DISTINCT CO2.company_id ) > 1)
And not Exists (Select * from company_officer
Where Company_Id = cd.Company_Id
Having count(*) < 1)
ORDER BY `CD`.`Company_Name` ASC, `CD`.`Company_ID` ASC;
另外,您可以使用Exists
而不是In
SELECT CD.Company_ID, CD.Company_Name, CD.Company_Index,
OD.Officer_ID, OD.Officer_Name, CO.Officer_Role
FROM Company_Details CD
JOIN Company_Officer CO
ON CD.Company_ID = CO.Company_ID
JOIN Officer_Details OD
ON CO.Officer_ID = OD.Officer_ID
WHERE Not Exists
(Select * FROM Company_Officer
WHERE officer_id = od.officer_id
and Resigned_on = ''
Having count(*) <= 2)
And Not Exists
(Select * from company_officer
Where Company_Id = cd.Company_Id
Having count(*) <= 1)
ORDER BY `CD`.`Company_Name` ASC, `CD`.`Company_ID` ASC;