簡體   English   中英

從集合中查找列中缺少的值(mysql)

[英]Find values missing in a column from a set (mysql)

我正在使用mysql。

我有一個具有列ID的表。

假設我有一組輸入ID。 我想知道表格中缺少哪些所有ID。

如果集合為“ ida”,“ idb”,“ idc”,並且表僅包含“ idb”,則返回值應為“ ida”,“ idc”。

單個sql查詢可能嗎? 如果沒有,執行此操作的最有效方法是什么。

請注意,我不允許使用存儲過程。

MySQL將僅返回存在的行。 要返回丟失的行,您必須有兩個表。

第一個表可以是臨時的(特定於會話/連接),因此多個實例可以同時運行。

create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida";
insert into tmpMustExist select "idb";
-- etc

select a.id from tmpMustExist as a
  left join table b on b.id=a.id
  where b.id is null; -- returns results from a table that are missing from b table.

單個sql查詢可能嗎?

好吧,是的。 讓我按自己的方式工作,首先用union allunion all來組合select語句。

create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;

請注意,我使用union allunion快一點,因為它跳過了重復數據刪除。

您可以使用create table ... select 我經常這樣做,真的很喜歡。 (這也是復制表的好方法,但是會刪除索引。)

create temporary table tmpMustExist as select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;

最后,您可以使用所謂的“派生”表將整個內容放入單個可移植的select語句中。

select a.id from (select "ida" union all select "idb" union all select "etc...") as a left join table as b on b.id=a.id where b.id is null;

注意: as關鍵字是可選的,但闡明了我對ab 我只是在創建短名稱以在joinselect字段列表中使用

//you can pass each set string to query
//pro-grammatically you can put quoted string
//columns must be utf8 collation

select * from
(SELECT 'ida' as col 
union  
SELECT 'idb' as col 
union  
SELECT 'idc' as col ) as setresult where col not in (SELECT value FROM `tbl`)

有個把戲。 您可以創建具有期望值的表,也可以對每個值使用多項選擇的並集。

然后,您需要找到標准具中的所有值,而不是測試表中的所有值。

CREATE TABLE IF NOT EXISTS `single` (
  `id` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `single` (`id`) VALUES
('idb');

SELECT a.id FROM (
   SELECT 'ida' as id
   UNION
   SELECT 'idb' as id
   UNION
   SELECT 'idc' AS id
) a WHERE a.id NOT IN (SELECT id FROM single)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM