Sql 查询返回笛卡尔积(Northwind)
我正在使用oracle中的northwind数据库 任务: 获取在每个区域工作的员工数量 结果: (地区名称、员工人数) 我正在尝试这个查询,但它返回笛卡尔积Sql 查询返回笛卡尔积(Northwind),sql,database,oracle,northwind,Sql,Database,Oracle,Northwind,我正在使用oracle中的northwind数据库 任务: 获取在每个区域工作的员工数量 结果: (地区名称、员工人数) 我正在尝试这个查询,但它返回笛卡尔积 select r.regiondescription, count(e.employeeid) from employees e, employeeterritories et, territories t, region r where r.regionid = t.regionid and et.t
select r.regiondescription, count(e.employeeid)
from employees e,
employeeterritories et,
territories t,
region r
where r.regionid = t.regionid
and et.territoryid = t.territoryid
and e.employeeid = et.employeeid
group by r.regiondescription;
问题:我的查询有什么问题?我能想到的唯一一件事是,您的一个表正在乘以结果,您应该使用count(DISTINCT):
哪些表之间的笛卡尔积?你的意思是它在分组之前返回笛卡尔积吗?你能发布一个数据样本和你现在得到的结果以及你的期望吗?我没有发现这个查询有任何错误。(好吧,你应该使用现代的显式连接语法而不是旧的隐式连接语法…)检查一下我已经上传了你的表中有多少员工?@rontornambe它已经在where子句中了,两次!为什么它返回笛卡尔积?你能解释一下吗?笛卡尔积是什么意思?是吗?是的,我是说multiplied@nafeesahmed如果其中一个表包含上述关系的1条以上记录(regionId/territoryId/empId),则每一行都将乘以此唯一ID的记录计数查询中的另一个错误(但可能不是OP正在查找的)是指在没有任何员工的地区或地区,缺少外部连接。如果问题陈述中显示了所有区域中的员工数量,则会忽略这些区域。
select r.regiondescription, count(distinct e.employeeid)
from employees e,
employeeterritories et,
territories t,
region r
where r.regionid = t.regionid
and et.territoryid = t.territoryid
and e.employeeid = et.employeeid
group by r.regiondescription;