【问题标题】:SQL selecting records from one table and using this as input to another table to delete recordsSQL 从一个表中选择记录并将其用作另一个表的输入以删除记录
【发布时间】:2011-09-22 15:53:19
【问题描述】:

我有带列的 table1:

def_id, def_name, username etc

我有另一个表 table2 有一些关联:

assoc_id,parent_id,child_id

parent_id 和 child_id 实际上是来自 Table1 的 def_id。它们根据 GUI 中的 parent_child 关系用户操作插入到 Table2 中。

现在我想从 Table1 中为特定用户名选择所有 def_id,然后使用该输入删除所有记录,如果这些 def_id 是 Table2 中 parent_id 或 child_id 的一部分。

如何在 SQL 中执行此操作?我正在使用 Sybase 数据库。

任何帮助将不胜感激

【问题讨论】:

    标签: sql sybase sql-delete


    【解决方案1】:
     Delete Table2
     Where parent_id In
         (Select def_id from table1
          Where username = @username) Or
         child_id In
         (Select def_id from table1
          Where username = @username)
    

    或者

      Delete t2
      From table2 t2
      Where Exists
         (Select * From Table1
          Where def_id In 
              (t2.parent_Id, t2.child_Id))
    

    【讨论】:

    • 感谢大家的回复。真的很感谢你帮助我。 Charles Bretana 的第一个答案对我有用,他建议的下一个查询给了我一个语法错误 SQL Anywhere 错误 -131:第 1 行的“Where”附近的语法错误谢谢 -C
    • 您可能需要添加一个 from 子句才能让第二个子句工作...我编辑显示...
    【解决方案2】:

    一种简单的方法是在 where 子句中添加子查询。

    DELETE ab
    FROM AuthorArticle AS ab
    WHERE ab.AuthID=(SELECT AuthID FROM Authors WHERE AuthorLastName='Yin')
    

    从未使用过 Sybase,但这是基本 SQL,应该可以工作。

    【讨论】:

      【解决方案3】:

      试试:

      DELETE table2
      FROM table2
      INNER JOIN table1 ON table1.def_id IN (table2.parent_id, table2.child_id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-26
        • 2022-01-21
        • 1970-01-01
        • 2012-01-23
        • 1970-01-01
        • 2010-11-29
        相关资源
        最近更新 更多