简体   繁体   English

有没有办法识别那些在IN()语句中找不到的记录?

[英]Is there a way to identify those records not found within a where IN() statement?

From PHP Code $Lines is defined as a list of accessions eg 123,146,165,1546,455,155 从PHP代码$ Lines定义为加入列表,例如123,146,165,1546,455,155

plant table has sequential records with the highest idPlant (unique identifier) of say 1000. 工厂表具有最高idPlant(唯一标识符)的连续记录,例如1000。

My simple SQL Query: 我的简单SQL查询:

SELECT * FROM plant WHERE `plant`.idPlant IN($Lines) order by plant.idPlant;

This brings back row data for '123,146,165' etc. 这将返回'123,146,165'等行数据。

Is there away to be told that '1546' was not found? 有没有被告知'1546'没有找到? (and thus the user probably entered a typo, I can not use a 'confirm all numbers are below X' because in the real data the idPlant may not be sequential and the upper bound will increase during use). (因此用户可能输入了拼写错误,我不能使用'确认所有数字都低于X',因为在实际数据中,idPlant可能不是顺序的,上限将在使用期间增加)。

Update: 更新:

Looking to get an output that will tell me what Numbers were not found. 希望得到一个输出,告诉我没有找到哪些数字。

You can build up a sub query using unions that returns a list of all your values, then LEFT JOIN against that, checking for NULL in the WHERE clause to find the non matching values. 您可以使用联合构建子查询,该联合返回所有值的列表,然后对此进行LEFT JOIN,在WHERE子句中检查NULL以查找不匹配的值。

Basic php for this would be something like this:- 这个基本的PHP将是这样的: -

<?php

$sub_array = explode(',', $Lines);

$sub = '(SELECT '.implode(' AS i UNION SELECT ', $sub_array).' AS i) sub0';

$sql = "SELECT sub0.i 
    FROM $sub
    LEFT OUTER JOIN plant 
    ON  plant.idPlant = sub0.i 
    WHERE plant.idPlant IS NULL";

?>

You can create a temporary table and compare it to the original table. 您可以创建临时表并将其与原始表进行比较。 It goes something like this: 它是这样的:

CREATE TEMPORARY TABLE IF NOT EXISTS plantIDs  (
    ID INT(11) NOT NULL UNIQUE,
    found INT(11) NOT NULL);

INSERT INTO plantIDs(ID) VALUES (123),(146),(165),(1546),(455),(155);

SELECT plantIDs.ID, COALESCE(plant.name, "Not Found") as PlantName, plant.* FROM plant RIGHT JOIN plantIDs ON plant.idPlant=plantIDs.ID ORDER BY plantIDs.ID;

Assuming you have a field named name inside the table plant , this code will produce a row for each plant and the column named PlantName will contain the name of hte plant or the text "Not Found", ofc you can change the coalesce value to anything that fits your needs. 假设您在表plant有一个名为name的字段,此代码将为每个工厂生成一行,名为PlantName的列将包含hte工厂的名称或文本“Not Found”,您可以将coalesce值更改为任何内容这符合您的需求。

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

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