2016-05-12 4 views
0

私はmysqlを使用しています。セットの列に値が見つからない(mysql)

私はカラムIDを持つテーブルを持っています。

私はidsの入力セットを持っているとしましょう。私はすべてのIDがテーブルにないことを知りたい。

セットが "ida"、 "idb"、 "idc"で、テーブルに "idb"のみが含まれている場合、戻り値は "ida"、 "idc"になります。

これは単一のSQLクエリで可能ですか?そうでない場合は、これを実行する最も効率的な方法は何ですか。

ストアドプロシージャは使用できません。

+1

これはアプリケーションコードで簡単に行うことができます。どのようなプログラミング言語を使用していますか? – tadman

+0

'' id ''、 'idb'、 'idc') ' –

+0

のようなサウンド' SELECT a.id FROM input_set a LEFT JOINテーブルb ON a.id = b.id WHERE b.id IS NULL' – Serg

答えて

2

MySQLは存在する行のみを返します。欠落している行を戻すには、2つの表が必要です。

最初のテーブルは、複数のインスタンスを同時に実行できるように、一時的(セッション/接続固有)にすることができます。

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 allselectステートメントを組み合わせると私の方法を働かせてください。それは重複排除をスキップしているためunionよりも少し速いです私はunion allを使用

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; 

注意。

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 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でやって明確にしています。私は単純なトリックがあります

0
//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`) 
0

joinselectフィールドリストで使用される短い名前を作成しています。期待値で表を作成するか、値ごとに複数選択の和集合を使用することができます。

次に、エタロン内のすべての値を検索する必要がありますが、テスト対象のテーブルにはありません。

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) 
関連する問題