mysql 如何删除未加卡的用户?

ryevplcw  于 2023-05-21  发布在  Mysql
关注(0)|答案(2)|浏览(126)

我有以下查询:

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

它返回尚未添加任何卡的用户。我需要删除这些用户(从users)表。下面是我的delete查询:

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 )

但它会抛出以下错误:

1093 -无法在FROM子句中指定更新的目标表'users'

我该怎么解决?

q5iwbnjs

q5iwbnjs1#

不需要使用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;
k4emjkb1

k4emjkb12#

您可以选择使用取反的EXISTS运算符。

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

相关问题