MySQL-从数字列表中选择在表的id字段中没有对应项的那些 [英] MySQL - Select from a list of numbers those without a counterpart in the id field of a table

查看:158
本文介绍了MySQL-从数字列表中选择在表的id字段中没有对应项的那些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表,例如{2,4,5,6,7} 我有一个带有foos.ID的表foos,其中包括{1,2,3,4,8,9}

I have a list of numbers, say {2,4,5,6,7} I have a table, foos, with foos.ID, including say, {1,2,3,4,8,9}

Id喜欢获取我的数字列表,并在我的表格的ID字段中找到没有对应的数字.

Id like to take my list of numbers, and find those without a counterpart in the ID field of my table.

一种实现此目的的方法是创建一个表栏,在ID字段中加载{2,4,5,6,7}. 然后,我会做

One way to achieve this would be to create a table bars, loaded with {2,4,5,6,7} in the ID field. Then, I would do


SELECT bars.* FROM bars LEFT JOIN foos ON bars.ID = foos.ID WHERE foos.ID IS NULL

但是,我想完成这个临时表.

However, I'd like to accomplish this sans temp table.

有人对它如何发生有任何意见吗?

Anyone have any input on how it might happen?

推荐答案

这是一个很常见的问题:在不创建表的情况下即时生成关系.用于此问题的SQL解决方案非常尴尬.使用派生表的一个示例:

This is a problem that is pretty common: generating a relation on the fly without creating a table. SQL solutions for this problem are pretty awkward. One example using a derived table:

SELECT n.id
FROM
  (SELECT 2 AS id 
   UNION SELECT 3 
   UNION SELECT 4 
   UNION SELECT 5 
   UNION SELECT 6 
   UNION SELECT 7) AS n
  LEFT OUTER JOIN foos USING (id)
WHERE foos.id IS NULL;

但这并不能很好地扩展,因为您可能有很多值,而不仅仅是六个.构造一个长列表,每个值需要一个UNION,这可能会很烦人.

But this doesn't scale very well, because you might have many values instead of just six. It can become tiresome to construct a long list with one UNION needed per value.

另一种解决方案是保留一个由十位数字组成的通用表,并将其重复用于多种目的.

Another solution is to keep a general-purpose table of ten digits on hand, and use it repeatedly for multiple purposes.

CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

SELECT n.id
FROM 
  (SELECT n1.i + n10.i*10 AS id
   FROM num AS n1 CROSS JOIN num AS n10
   WHERE n1.i + n10.i*10 IN (2, 3, 4, 5, 6, 7)) AS n
  LEFT OUTER JOIN foos USING (id)
WHERE foos.id IS NULL;

我展示了内部查询从0..99生成值,即使在这种情况下这不是必需的.但是您的列表中的值可能大于10.关键是,使用一个表num,您可以生成大量数字,而不必求助于每个值一个UNION的很长的链.另外,您可以在一处指定所需值的列表,这更加方便和可读.

I show the inner query generating values from 0..99 even though this isn't necessary for this case. But you might have values greater than 10 in your list. The point is that with one table num, you can generate large numbers without having to resort to very long chains with one UNION per value. Also, you can specify the list of desired values in one place, which is more convenient and readable.

这篇关于MySQL-从数字列表中选择在表的id字段中没有对应项的那些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆