【问题标题】:Count and IN Clause Issue计数和 IN 子句问题
【发布时间】:2013-08-31 22:43:45
【问题描述】:

我有一个名为员工历史的表,其结构如下。

tbl_employee_history 结构

id|history_nr|history_value|employee_id
1   82         83             1
2   86         84             1 
3   87         85             1
4   603                       1
5   82         83             2
6   86         83             2
7   87         83             2
8   603        83             2

这是我的表格的虚拟数据。现在我想计算所有那些 history_nr 在 82,86,87,603 并且 history_value 不应该为空的员工,就像上面的例子一样,计数应该是 1,因为员工 id 2 所有的值都不为空。这是我实现计数的查询。

SELECT count(employee_id) FROM tbl_employee_history where history_nr IN(82,86,87,603) AND history_value!=''

但是发生的情况是计数返回了两个值。 提前致谢。

【问题讨论】:

  • 我模拟了你的数据库和查询,我得到了 7 个数。你的代码还有更多吗?听起来您要么在分组,要么在寻找不同的值。
  • 是的,我正在寻找不同的值,我想选择那些在 in 子句中提到的所有历史值都不应该为空的不同员工,如果 in 子句中提到的任何值为空,那么它不应该考虑。查询是 select count(distinct(employee_id)) where history_Value in (82,86,603,87) and history_value!=''

标签: php mysqli in-clause


【解决方案1】:

删除查询中的distinct() 部分,这将只返回唯一值。由于employee_id 1 和 2 各有 4 行,因此它只会抓取具有不同(唯一)employee_id 的第一行。

因此它只提取 2 条记录,每个 employee_id 一条。

SELECT count(employee_id) FROM tbl_employee_history where history_nr IN(82,86,87,603) AND history_value != ''
//Returns 7 Rows

SELECT count(distinct(employee_id)) FROM tbl_employee_history where history_nr IN(82,86,87,603) AND history_value != ''
//Returns 2 Rows

【讨论】:

  • 我已经在我的系统中实现了第二个查询,但问题是它从上述数据中返回了两个。我想在这里实现的是,如果任何 history_nr 值是空的,比如员工 1 的 id 4 是空的,它甚至不应该考虑计数中的员工。所以正确的计数是 1 而不是 2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
  • 2022-12-11
相关资源
最近更新 更多