简体   繁体   English

MySQL计数不删除

[英]Mysql count without deleted

I have an sql query that simply adds a row to an existing database table. 我有一个SQL查询,只是将一行添加到现有数据库表中。 The first field is id and I assume this value has to be specified in the query. 第一个字段是id ,我假设必须在查询中指定此值。

So then id has to be the number of rows existing + 1. I'm determining the id like this: 因此,id必须是现有的行数+1。我要像这样确定id:

SELECT COUNT(1) FROM testtable

The problem is that this returns the number of rows that have ever been added, including deleted ones. 问题在于这将返回已添加的行数,包括已删除的行数。 Because I have been adding and removing from this table, this number is greater than the number of EXISTING rows in the table which is what I want. 因为我一直在向该表添加和删除,所以该数目大于我想要的表中现有行的数目。

How can I count the existing rows in the table instead of the existing + deleted rows? 如何计算表中的现有行,而不是现有+删除的行?

If possible switch to using an auto_increment column for your id and don't be concerned with gaps in the sequence of ids. 如果可能,请切换为对id使用auto_increment列,而不用担心id序列中的间隔。 Your own implementation of id generation may inflict more harm especially in a long run. 您自己的id生成实现可能会造成更大的危害,尤其是从长远来看。

Now, back to your immediate question. 现在,回到您的紧迫问题。 You are probably looking for this 您可能正在寻找这个

SELECT MAX(id) + 1 new_id 
  FROM Table1

Note: This query might fail under heavy load when several concurrent sessions issuing this query might grab the same id and your subsequent INSERT will fail. 注意:当发出此查询的多个并发会话可能获取相同的ID并且您随后的INSERT将失败时,此查询在重负载下可能会失败。 Therefore again consider using an auto_increment for your id. 因此,请再次考虑使用auto_increment作为您的ID。

Here is SQLFiddle demo 这是SQLFiddle演示

That's a bad idea, because you can end up with duplicate IDs, especially if you delete rows in the middle. 这是个坏主意,因为您可能会得到重复的ID,尤其是如果删除中间的行。 If you're not going to use an auto-increment field, you can add the ID to the insert. 如果您不打算使用自动递增字段,则可以将ID添加到插入内容中。 Just use this in place of the value: 只需使用它代替值即可:

((SELECT MAX(t.id) + 1 FROM table t)

The full query would then be: 完整的查询将是:

INSERT INTO table_name (id, col1, col2, col3) VALUES ((SELECT MAX(t.id) + 1 FROM table_name t), :col1, :col2, :col3)
SELECT COUNT(*) from table

将仅返回其中的条目数,而不基于ID

There is also possibility to find, and fill the gaps, by picking first free id 还可以通过选择第一个免费ID来找到并填补空白

SELECT MIN(t1.id + 1) AS free_id
FROM t1
WHERE NOT EXISTS (SELECT t2.id FROM t2 WHERE t2.id = t1.id + 1)

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

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