【问题标题】:SQL algorithm with three identifiers from one table一张表的三个标识符的 SQL 算法
【发布时间】:2014-05-29 09:08:34
【问题描述】:

这可能真的很容易,但我不知道如何通过一个查询从我的数据库中获取必要的值。只是现在想不通。我将在 CodeIginiter 系统中进行此查询。

表'信息'构造:

CREATE TABLE information (
    planid int(11) NOT NULL,
    production_nr int(11) NOT NULL,
    status int(11) NOT NULL
);

表'信息'内容:


必要的输出: 我想获得(最好 - 只有一个查询,但如果不可能,则有多个)所有 planid 的 where:所有这个计划 id 的 pruduction_nrs 的状态 >= 3。

在这种情况下,我需要获取这些 planid 的:2 和 5,因为这些 planid 的 ALL production_nrs 中的每一个都具有大于或等于 3 的状态。

【问题讨论】:

    标签: sql database algorithm codeigniter


    【解决方案1】:
    select planid, production_nr
    from information inf1
    where not exists (select 1 from information inf2
                      where inf1.planid = inf2.planid
                      and   status < 3)
    

    您可以根据需要考虑修改 select 子句(第一行):

    • 添加 distinct(如果表 PK 包含状态列)

    • 更改列列表

    【讨论】:

    • 查询的执行计划可能是: 1. 主查询执行顺序全表扫描。 2. 对于每一行,子查询将检查给定的 planid 是否有不符合要求状态的行 >= 3. 在第一行发现子查询停止。
    【解决方案2】:

    试试这个,

    SELECT planid , production_nr FROM  information
    WHERE production_nr IN(SELECT production_nr FROM information) AND STATUS >=3
    

    【讨论】:

      【解决方案3】:

      您的问题被称为关系划分。基本上有两种方法可以接近它

      1) 不存在的 planid 状态为 的 production_nr

      select planid 
      from information i1
      where not exists (
          select 1 from information i2
          where i1.planid = i2.planid
            and i2.planid < 3
      ) 
      

      2) planid,其中 production_nr 的数量等于 status >= 3 的 production_nr 的数量。我将把它作为练习 ;-)

      【讨论】:

        猜你喜欢
        • 2021-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2013-08-13
        相关资源
        最近更新 更多