[英]SQL how to find keys not in use in several tables
SQL, a table (thesau) with terms that may or may not be in use in several other tables. SQL,一个表(thesau),其中包含可能在其他几个表中使用或可能不使用的术语。 The other tables point to the id in thesau.
其他表指向叙词表中的id。 I want to find out which terms are NOT in use, ie which terms are not referred to by any other table.
我想找出未使用的术语,即任何其他表格未提及的术语。 Simplified:
简化:
table: thesau
id term
1 painting
2 sari
4 oil
5 silk
8 gouache
table: object_type
id
1 (-> painting)
7 (-> ... )
table: material_type:
id
2 (-> silk)
4 (-> oil)
in collection, object_type 1 refers to thesau 1 = painting, and so on. 在集合中,object_type 1表示主题1 =绘画,依此类推。 Now, I can find thesau terms not in use in one single table, like so:
现在,我可以在一个表中找到未使用的词库术语,如下所示:
select distinct thesau.id, thesau.term from thesau_term
where thesau_term.id not in
(select object_type.id from object_type)
This works. 这可行。 I want to expand the same query to other tables, in one query if possible.
我想将同一查询扩展到其他表,如果可能的话,在一个查询中。 In pseudo-code:
用伪代码:
select distinct id, term from thesau_term
where thesau_term.id not in
((select object_type.id from object_type) or
(select material_type.id from material_type))
This doesn't work. 这行不通。 What am I missing?
我想念什么?
Your current query would list a term that is not in use in at least one other table. 您当前的查询将列出至少一个其他表中未使用的术语。 If you use
AND
instead of OR
, your query would list terms not in use in any other table: 如果使用
AND
而不是OR
,则查询将列出任何其他表中未使用的术语:
select distinct id, term from thesau_term
where thesau_term.id not in
((select object_type.id from object_type) AND -- <<== HERE
(select material_type.id from material_type))
You can further simplify your query by using NOT EXISTS
您可以使用
NOT EXISTS
进一步简化查询
SELECT id, term
FROM thesau_term t
WHERE
NOT EXISTS (SELECT * FROM object_type ot WHERE ot.id=t.id)
AND NOT EXISTS (SELECT * FROM material_type mt WHERE mt.id=t.id)
or by using an outer join 或使用外部联接
SELECT DISTINCT t.id, t.term
FROM thesau_term t
LEFT OUTER JOIN object_type ot ON ot.id=t.id
LEFT OUTER JOIN material_type mt ON mt.id=t.id
WHERE ot.id IS NULL and mt.id IS NULL
You don't need to use a join
, you can do what you have done in your first query, you just need to change the where
clause. 您不需要使用
join
,您可以执行在第一个查询中所做的事情,只需要更改where
子句即可。 A not exists
would be the most permanent but something like this would work: not exists
将是最永久的,但类似的方法将起作用:
SELECT DISTINCT
id,
term
FROM thesau_term
WHERE thesau_term.id NOT IN
(
SELECT object_type.id
FROM object_type
)
OR thesau_term.id NOT IN
(
SELECT material_type.id
FROM material_type
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.