【问题标题】:Mysql for each row check to use if a field is in another table and if not delete that rowMysql 为每一行检查是否一个字段在另一个表中,如果不删除该行
【发布时间】:2021-09-22 01:35:05
【问题描述】:

我有两个表,第一个称为“用户”,第二个称为“配置文件”。两个表都有一个名为“id”的字段,profiles 表还有一个名为“user_id”的字段,我用它来连接两个表。长话短说,当用户被删除时,他们的配置文件不是(该问题已得到解决),我想在配置文件表中找到没有用户连接到他们的所有配置文件。我需要以某种方式检查配置文件表中的每一行,以查看字段“id”下的“用户”表中是否存在“user_id”字段,以及它是否不删除配置文件表中包含该“user_id”的行.

【问题讨论】:

    标签: mysql sql loops each


    【解决方案1】:

    你可以使用not exists:

    select p.*
    from profiles p
    where not exists (select 1 from users u where p.profile_id = u.id);
    

    如果要删除行:

    delete p from profiles p
    where not exists (select 1 from users u where p.profile_id = u.id);
    

    【讨论】:

    • 非常感谢,这正是我所需要的,如果你不介意我问,“p”和“u”代表什么? ('profiles p') ,('users u') , ('p.profile_id') 和 ('u.id')
    • @HelpmeJohn 。 . .这些是表别名。它们在这里仅用作表名的缩写,因此查询更易于编写和阅读。
    猜你喜欢
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多