【问题标题】:How can I retrieve all rows which depend on other rows in the same table?如何检索依​​赖于同一表中其他行的所有行?
【发布时间】:2020-06-02 05:13:02
【问题描述】:

所以我有这个表格方案

|id| item_id | dependency_item_id | completed |

想法是让这个表中的行通过dependency_item_id -> item_id指向同一个表中的其他行。

我想要的是检索所有具有 dependency_item_id 的记录,其值为 NULLcompleted 的值为 0

所有具有父级的记录,即具有item_id = dependency_item_id 的行,状态为completed = 1 及其状态为completed = 0

例子:

These are the records in the database.
|id|task_id|dependency_item_id|completed|
|1 |1      |null              |1        |
|2 |2      |null              |0        |
|3 |3      |1                 |0        |
|4 |4      |2                 |0        |
|5 |5      |2                 |0        |

With the query we should get only the second record
|id|task_id|dependency_item_id|completed|
|2 |2      |null              |0        |
|3 |3      |1                 |0        |

此时我的查询如下:

SELECT process.* 
    FROM tasks AS tasks 
        JOIN tasks AS dep ON dep.dependency_item_id = process.task_id 
    WHERE (dep.completed = 1 and tasks.completed = 0) OR tasks.dependency_item_id IS NULL

【问题讨论】:

  • 自己加入表。
  • StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • 当你得到一个你不期望/不理解的结果时,停止试图找到你的总体目标并找出你的误解是什么。--隔离第一个意外/误解的子表达式及其输入 &输出并了解是什么误解、错字、错误推理等导致了它。 (调试基础。)问这个。

标签: mysql sql database join


【解决方案1】:

您可以自行加入表格:

select t.*
from mytable t
left join mytable d on d.id = t.dependency_item_id
where 
    (t.dependency_item_id is null and t.completed = 0)
    or (d.dependency_item_id is null and d.completed = 0)

【讨论】:

    【解决方案2】:

    这是您需要相关子查询的情况。

    Select * from items as I where (dependency_item is null and completed = 0 )
    OR 
    item_id in (Select item_id from items as S where I.dependency_item = S.item_id and
    I.completed = 0 and S.completed = 1)`
    

    【讨论】:

      【解决方案3】:

      我不得不调整您给我的查询以满足我的需要,因为使用给定的查询我无法检索具有空依赖项的记录。我的最终结果如下:

      SELECT dep.* 
          FROM tasks AS task 
              LEFT JOIN tasks AS dep ON dep.dependency_item_id = task.item_id 
          WHERE (task.completed = 1 and dep.completed = 0) 
      UNION 
      SELECT * FROM tasks WHERE dependency_item_id IS NULL AND completed = 0
      

      【讨论】:

        猜你喜欢
        • 2014-07-02
        • 1970-01-01
        • 1970-01-01
        • 2015-09-19
        • 2021-12-13
        • 2017-03-28
        • 2021-07-10
        • 1970-01-01
        • 2014-11-16
        相关资源
        最近更新 更多