首页 > 解决方案 > 复杂的删除

问题描述

我想删除表中的一些行。但是删除条件不是直接的。这只是 1 个表 CUSTOMER:

CREATE TABLE customer (
    CUST_ID int(11) NOT NULL AUTO_INCREMENT,
    PRODUCT_CODE varchar(50) NOT NULL,
    USER_NAME varchar(150) NOT NULL,
    PRIMARY KEY (CUST_ID)
) ENGINE=InnoDB AUTO_INCREMENT=2455046 DEFAULT CHARSET=latin1;

这对我有用:

select cust_id from CUSTOMER where user_name = '20012';

然后在下面的 DELETE 中使用生成的 cust_id($cust_id 是查询 1 的结果)

delete from CUSTOMER where cust_id = $cust_id 

注意:这只能删除一个 user_name 。我也想在 1 个查询中执行此操作,而不是 2 个。

  CUSTOMER t1
  LEFT JOIN (
    SELECT
      cust_id id
    FROM
      CUSTOMER
    where
      user_name IN ('20012', '20013', '20014')
  ) t2 ON t1.cust_id = t2.id

以上显然没有奏效。

标签: mysql

解决方案


您不必要地使逻辑复杂化。对于给定的 user_name 值,您可以简单地过滤 user_name 值,而不是首先获取所有客户 ID。就是这样:

DELETE FROM CUSTOMER WHERE user_name IN ('20012', '20013', '20014')

推荐阅读