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

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

How to delete users who have not added card?

问题

Here's the translated code snippet:

  1. 我有以下查询:
  2. 选择 u.*
  3. 从用户 u
  4. 左连接 customers_cards cc
  5. cc.user_id = u.id
  6. 其中 u.belongs_to = "ezpay"
  7. 并且 cc.id 是空的
  8. 它返回尚未添加任何卡的用户。我需要从“users”表中删除这些用户。因此,这是我的“删除”查询:
  9. 从用户中删除
  10. 其中 id 在(选择 u.id
  11. 从用户 u
  12. 左连接 customers_cards cc
  13. cc.user_id = u.id
  14. 其中 u.belongs_to = "ezpay"
  15. 并且 cc.id 是空的)
  16. 但它抛出以下错误:
  17. > #1093 - 你不能在FROM子句中指定目标表'users'进行更新
  18. 如何修复它?
英文:

I have the following query:

  1. select u.*
  2. from users u
  3. left join customers_cards cc
  4. on cc.user_id = u.id
  5. where u.belongs_to = "ezpay"
  6. 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:

  1. delete from users
  2. where id in ( select u.id
  3. from users u
  4. left join customers_cards cc
  5. on cc.user_id = u.id
  6. where u.belongs_to = "ezpay"
  7. 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语句:

  1. delete u.*
  2. from users u
  3. left join customers_cards cc
  4. on cc.user_id = u.id
  5. where u.belongs_to = "ezpay"
  6. 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:

  1. delete u.*
  2. from users u
  3. left join customers_cards cc
  4. on cc.user_id = u.id
  5. where u.belongs_to = "ezpay"
  6. and cc.id is null;

答案2

得分: 1

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

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

You can optionally use the negated EXISTS operator.

  1. DELETE FROM users
  2. WHERE NOT EXISTS(SELECT 1
  3. FROM customer_cards
  4. WHERE users.id = customer_cards.id)
  5. 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:

确定