【问题标题】:Count the number of times of component replacement计算组件更换次数
【发布时间】:2018-09-05 11:49:40
【问题描述】:

我想在“每个组件发生替换的次数”上找到计数。

例如,

Component_ID | Replacement_ID
001          |    NULL
002          |     001
003          |     002
004          |     003
005          |     Null

结果:

Component_ID | Number of time a replacement already occurred
   004       |    3
   005       |    0

【问题讨论】:

  • 听起来你需要递归逻辑。
  • 如果我有存储过程或函数会有帮助吗?
  • @momoni:两列中的 ID 是唯一的吗?
  • @zarruq replacement_id 是旧的 component_ID 。是的,它是独一无二的。

标签: mysql sql stored-procedures logic mysql-workbench


【解决方案1】:

通常你应该至少有两张桌子。 components 表,其中包含以 Component_ID 作为主要字段的组件以及其他字段(例如 component_name)和另一个可能称为 component_replacements 的表 包含一个主要字段 ID,例如 component_replacement_id 以及 component_id 和其他字段,例如更换日期。 Component_ids 可以在此表中出现多次。这将允许您进行基本查询,例如:

SELECT Component_ID, IFNULL( total,0) replacements FROM
            (
              SELECT Component_ID, COUNT(*) total
                   FROM component_replacements GROUP BY Component_ID
            ) replacements ON components.Component_ID = replacements.Component_ID

【讨论】:

  • 我只有 1 个表 .. 是否可以执行 if 循环或 while 循环?
  • 你想做一个循环,这样你就可以计数。这正是 SQL 中存在 GROUP By 子句的原因,这样您就不必做这些事情了。如果可以的话,如果您以允许您回答此类问题的方式设计数据库,那将很容易。请记住,数据库不仅用于存储,它还应该提供报告和回答您有关其包含的数据的问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2015-06-18
相关资源
最近更新 更多