简体   繁体   English

SQL:对于每一行,请检查涉及该行元素的条件

[英]SQL: For each row, check a condition involving an element of that row

I am looking to do something along the lines of: 我希望按照以下方式做一些事情:

For each row in a table, check if there are children (this is done by selecting all elements with a parentid equal to the current element's id). 对于表中的每一行,检查是否有子代(通过选择所有父代号等于当前元素的ID的元素来完成此操作)。 If nothing shows up, then there are no children and the parent needs to get deleted. 如果未显示任何内容,则说明没有子代,并且需要删除父代。 This parentid needs to come from the id of the current element. 该父ID必须来自当前元素的ID。

I was thinking something along the lines of (in pseudo-code-ish): 我在想一些类似的事情(在伪代码中):

DELETE FROM table WHERE ((SELECT * FROM table WHERE parentid = id) IS NULL)

Ideally, I would do a for each loop, and create a variable (note I'm writing this in C#) for the current id to use for the parentid search. 理想情况下,我将为每个循环执行一个操作,然后为当前ID创建一个变量(请注意,我正在用C#编写此变量)以用于父代搜索。

I think I may be overlooking an easier approach... Is there a easier way to implement this? 我想我可能会忽略一种更简单的方法...有没有更简单的方法来实现呢? If not, is the approach I have correct, and how could I translate this to SQL? 如果不是,我的方法正确吗?如何将其转换为SQL?

Either way any help is appreciated. 无论哪种方式,我们都会感激任何帮助。

Not sure this would be the right syntax, but what you are looking for is a list of all parentid s - this can be queried from table by fetching all parentid values from it. 不确定这是否是正确的语法,但是您要查找的是所有parentid的列表-可以通过从table获取所有parentid值来从table查询。 Once you have this list, you want to delete all items that are not in it and do not have a parentid of their own: 拥有此列表后,您想删除其中存在且没有parentid项的所有项目:

DELETE FROM table
WHERE id NOT IN
(
  SELECT parentid FROM table
)
AND parentid IS NULL -- assumption: parents do not have a parent id

Selecting rows that have no children with not exists() : 选择不包含not exists()子元素的行not exists()

--delete t
select *
from tbl t
where not exists (
  select 1
  from tbl i
  where t.id = i.parentid
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM