doufei8250 2017-06-10 00:45
浏览 46
已采纳

SQL - 根据另一个表中的行数删除行

How would I go about deleting a row from the table 'subjects' that has a primary id 'subject_id' based on the number of rows in another table named 'replies' that uses a 'subject_id' column as a reference.

Example in pseudo code: If ('subject' has less than 1 reply){ delete 'subject'}

I don't know much about SQL triggers so I have no clue if I would be able to incorporate this directly in the database or if I'd have to write some PHP code to handle this...

  • 写回答

4条回答 默认 最新

  • dopuzf0898 2017-06-10 01:20
    关注

    To delete any subjects that have had no replies, this query should do the trick:

    DELETE s.* FROM subjects AS s
    WHERE NOT EXISTS 
        (
        SELECT r.subject_id
        FROM replies AS r
        WHERE r.subject_id = s.subject_id
        );
    

    Demo: DB Fiddle Example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型