简体   繁体   English

删除 MySQL 中没有唯一 ID 的行

[英]Delete rows without unique id in MySQL

I have a table with the following columns: ClientID, Amount, etc. The problem is that some clients have two or more rows with Amount = 0 , and I want to remove these rows.我有一个包含以下列的表:ClientID、Amount 等。问题是某些客户端有两行或多行Amount = 0 ,我想删除这些行。 I've searched some information but only found with unique identification.我搜索了一些信息,但只找到了唯一标识。

Sample input :样本输入

ClientID客户编号 Amount数量
QER1 QER1 531 531
QER2 QER2 521 521
QER3 QER3 0 0
QER4 QER4 231 231
QER2 QER2 0 0
QER1 QER1 0 0

Expected Output :预期 Output

ClientID客户编号 Amount数量
QER1 QER1 531 531
QER2 QER2 521 521
QER3 QER3 0 0
QER4 QER4 231 231
DELETE t1 FROM clients t1
INNER JOIN clients t2 
WHERE 
    t1.ClientID = t2.ClientID AND
    t1.Amount = 0

The code you are looking for is this:您正在寻找的代码是这样的:

DELETE t1 FROM <table_name> t1 
INNER JOIN <table_name> t2 ON t1.ClientID = t2.ClientID AND t2.Amount > t1.Amount
WHERE t1.`Amount` = 0  ;

This will only remove rows if they have Amount = 0 and there is another amount with the same ClientId that is more than zero.这只会在行的数量 = 0 并且具有相同 ClientId 且大于零的另一个数量时删除行。

  • If a ClientID appears only once nothing is deleted.如果 ClientID 仅在没有删除任何内容时出现。
  • If a ClientID has a maximum Amount of zero nothing is deleted.如果 ClientID 的最大数量为零,则不会删除任何内容。

This second point may cause you issues, you can have ClientID with two rows of Amount = 0. If this is a problem you can Create a unique index which will clear this for you at the structural level:第二点可能会导致您出现问题,您可以让 ClientID 具有两行 Amount = 0。如果这是一个问题,您可以创建一个唯一索引,它将在结构级别为您清除它:

ALTER IGNORE TABLE table
ADD UNIQUE INDEX unqiueness (ClientID, Amount);

Your problem is that if you have two identical rows (ClientID and Amount = 0) then there is no unqiue identifier to distinguish and only remove one of those rows, this is not something we can fix at the query level (ie by running queries on the data) but is a core structural problem with your database design.您的问题是,如果您有两个相同的行(ClientID 和 Amount = 0),则没有唯一的标识符来区分并且只删除其中一个行,这不是我们可以在查询级别解决的问题(即通过在数据),但它是数据库设计的核心结构问题。 You should have a unique index id for each row, typically called a Primary Key.每行都应该有一个唯一的索引 ID,通常称为主键。

Indexing your Amount column is recommended.建议为您的金额列编制索引。 Also adding a unique row identifier (Primary Key) is also highly recommended .强烈建议添加唯一的行标识符(主键)。

You can view this SQL in action here .您可以在此处查看此 SQL 的运行情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM