删除未添加信用卡的用户。

huangapple go评论50阅读模式
英文:

How to delete users who have not added card?

问题

Here's the translated code snippet:

我有以下查询:

    选择 u.*
    从用户 u
    左连接 customers_cards cc
       cc.user_id = u.id 
    其中 u.belongs_to = "ezpay"
      并且 cc.id 是空的

它返回尚未添加任何卡的用户。我需要从“users”表中删除这些用户。因此,这是我的“删除”查询:

    从用户中删除
    其中 id 在(选择 u.id
                  从用户 u
                  左连接 customers_cards cc
                     cc.user_id = u.id 
                  其中 u.belongs_to = "ezpay"
                    并且 cc.id 是空的)

但它抛出以下错误:

> #1093 - 你不能在FROM子句中指定目标表'users'进行更新

如何修复它?
英文:

I have the following query:

select u.*
from users u
left join customers_cards cc
  on cc.user_id = u.id
where u.belongs_to = "ezpay"
  and cc.id is null

It returns users who have not added any card yet. I need to delete these users (from users) table. So here is my delete query:

delete from users
where id in ( select u.id
              from users u
              left join customers_cards cc
                on cc.user_id = u.id
              where u.belongs_to = "ezpay"
                and cc.id is null )

But it throws the following error:

> #1093 - You can't specify target table 'users' for update in FROM clause

How can I fix it?

答案1

得分: 1

没有必要使用IN运算符,因为您的SELECT语句可以转换为DELETE语句:

delete u.*
from users u
left join customers_cards cc
  on cc.user_id = u.id
where u.belongs_to = "ezpay"
  and cc.id is null;
英文:

There is no need to use the IN operator because your SELECT statement can be transformed into a DELETE statement:

delete u.*
from users u
left join customers_cards cc
  on cc.user_id = u.id
where u.belongs_to = "ezpay"
  and cc.id is null;

答案2

得分: 1

你可以选择使用否定的 EXISTS 操作符。

DELETE FROM users
WHERE NOT EXISTS(SELECT 1 
                 FROM customer_cards 
                 WHERE users.id = customer_cards.id)
  AND belongs_to = "ezpay"
英文:

You can optionally use the negated EXISTS operator.

DELETE FROM users
WHERE NOT EXISTS(SELECT 1 
                 FROM customer_cards 
                 WHERE users.id = customer_cards.id)
  AND belongs_to = "ezpay"

huangapple
  • 本文由 发表于 2023年5月21日 17:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定