简体   繁体   English

返回不存在的ID

[英]Return non existing IDs

I have a list of IDs and I write a MYSQL query to get information about these IDs. 我有一个ID列表,我编写了一个MYSQL查询来获取有关这些ID的信息。

What I need is a way to figure out which IDs are no longer in the database to delete them from the list of IDs. 我需要的是一种找出数据库中不再存在的ID的方法,以便从ID列表中删除它们。

Is there an easy solution to do that which I just can't think of right now? 有一个简单的解决方案可以做我现在无法想到的事情吗?

Create an additional (temporary) table, populate it with a list of IDs, and execute the query to find non existing id. 创建一个附加(临时)表,用ID列表填充它,然后执行查询以查找不存在的ID。 For example - 例如 -

CREATE TEMPORARY TABLE temp(id INT);
INSERT INTO temp VALUES (1), (2), (8), (10);

-- View non existing ID:
SELECT t.id FROM temp t
  LEFT JOIN your_table a 
    ON a.id = t.id
  WHERE a.id IS NULL;

DROP TEMPORARY TABLE IF EXISTS temp;

Then read this dataset in php application and update the list of IDs. 然后在php应用程序中读取此数据集并更新ID列表。

This is written not knowing your table structure, and thus making one up off the top of my head, but... 写这个是不知道你的表结构,因此使我头顶上的一个不完整,但是...

If you have two tables, ID and INFO, like: 如果您有两个表,ID和INFO,例如:

ID (IDCOL int, DATEENTERED datetime)
INFO (INFOID int, ID_ID int, ID_NAME varchar(50))

Then you could query 然后你可以查询

SELECT * FROM ID WHERE IDCOL NOT IN (SELECT ID_ID FROM INFO)

And that should return all entries in ID where there is not corresponding entry in INFO. 这应该返回ID中没有对应条目的ID中的所有条目。

After that it's a case of writing appropriate delete statements. 之后就是编写适当的delete语句的情况。

The whole thing could be done in one step with 整个过程可以一步完成

DELETE FROM ID WHERE IDCOL NOT IN (SELECT ID_ID FROM INFO)

But I generally prefer to do my deletes in defined transactions where you can examine to make sure you haven't screwed it up before you commit the changes to the DB. 但是我通常更喜欢在已定义的事务中进行删除,您可以在确定的事务中进行检查,以确保在将更改提交到数据库之前没有搞砸。

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

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