如何选择本示例中未使用的代码 [英] How select for not used codes in this sample

查看:113
本文介绍了如何选择本示例中未使用的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL数据库的表中有一个int列. 我在此表中保留了一些代码. 对于我的代码的示例范围是:(1,9).
我不需要在此范围内使用代码.

I have a int column in my table in a SQL database. I keep some of codes in this table. For sample range of my codes is : (1, 9).
I need to not used code in this range.

示例:
使用的代码是:

Example:
Used Codes is :

Select code from MyTable  -- result is 2,6,7,8,9

未使用的代码是:1、3、4、5

Not used codes is : 1,3,4,5

现在,如何选择此密码?预期结果是:1,3,4,5

Now , how can I select this codes? Expected result is : 1,3,4,5

推荐答案

为您的范围生成一个数字列表(在这里我使用VALUES子句),然后半联接到二手"列表

Generate a list of numbers for your range (here I use VALUES clause), then semi-join to the "used" list

SELECT
    *
FROM
   (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9)) X (Num)
WHERE
   NOT EXISTS (SELECT * FROM MyTable M WHERE M.Code = X.Num)

您可以将VALUES子句替换为任何数字表生成代码. 例子:

You can replace the VALUES clause with any number table generation code. Examples:

  • Optimizing Numbers Table Creation on SQL Server?
  • What is the best way to create and populate a numbers table?

这篇关于如何选择本示例中未使用的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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