【问题标题】:Query returns cartesian product (Northwind)查询返回笛卡尔积 (Northwind)
【发布时间】:2016-04-06 13:15:39
【问题描述】:

我在 oracle 中使用 northwind 数据库。

任务: 取号在每个地区工作的员工人数。

结果: (地区名称,员工人数)

我正在尝试这个查询,但它返回笛卡尔积

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;

问题:我的查询有什么问题?

【问题讨论】:

  • 哪些表之间的笛卡尔积?你的意思是在分组之前返回笛卡尔积吗?您能否发布一个数据样本以及您现在得到的结果以及您的预期?
  • 我找不到该查询有什么问题。 (嗯,你应该使用现代的显式 JOIN 语法,而不是旧的隐式连接语法......)
  • 检查一下我已经上传了
  • 您的表中有多少员工?
  • @rontornambe 它已经在 where 子句中了,两次!

标签: sql database oracle northwind


【解决方案1】:

我能想到的唯一一件事是,您的一张表正在将结果相乘,您应该使用 count(DISTINCT) 代替:

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;

【讨论】:

  • 为什么返回笛卡尔积你能解释一下吗?
  • 笛卡尔是什么意思?倍增?
  • 是的,我的意思是相乘
  • @nafeesahmed 如果其中一个表包含超过 1 条所提及的关系的记录(regionId/territoryId/empId),每行将乘以该唯一 ID 的记录数
  • 查询的另一个问题(但可能不是 OP 正在寻找的东西)是缺少外部连接,以防有没有任何员工的地区或地区。显示所有地区的员工人数的问题陈述将忽略这些地区。
猜你喜欢
  • 1970-01-01
  • 2017-06-29
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多