[英]How to get a list of unused/available primary keys (primary key ranges from 1 to 999) in an Oracle SQL table?
I have employee table where primary key empl_no ranges from 1 to 999. Now I want to know what primary_key are still available for adding new employee(s). 我有一个employee表,其中主键empl_no的范围是1到999。现在,我想知道哪些primary_key仍可用于添加新员工。 For example, below query returns the value 993. That means there are still 6 empl_no availavle which have not been used yet.
例如,下面的查询返回值993。这意味着仍有6个empl_no可用性尚未使用。 How can I get the list of those 6 available empl_no using Oracle SQL?
如何使用Oracle SQL获取这6个可用的empl_no的列表? Thanks in advance for you help :)
在此先感谢您的帮助:)
SELECT count(empl_no)
FROM emplpyee
WHERE empl_no BETWEEN 1 AND 999;
WITH cteNumbers AS (
SELECT LEVEL AS NUM
FROM DUAL
CONNECT BY LEVEL <= 999
)
SELECT n.NUM
FROM
cteNumbers n
LEFT JOIN emplpyee e
ON n.Num = e.empl_no
WHERE
e.empl_no IS NULL
Again don't re-use primary keys! 再次不要重复使用主键! But if you really want to know what is missing use a numbers table.
但是,如果您真的想知道丢失了什么,请使用数字表。 In ORACLE they make it easy using
CONNECT BY
. 在ORACLE中,它们使使用
CONNECT BY
变得容易。 Then LEFT JOIN
back to your table and look for when the empl_no
is missing. 然后将
LEFT JOIN
返回表中,并查找empl_no
丢失。
here is a link that shows oracle's ability to create a numbers table on the fly: http://rextester.com/CZDKC69208 这是一个链接,显示了oracle即时创建数字表的能力: http : //rextester.com/CZDKC69208
select level from dual connect by level <= 999
minus
select empl_no from emplpyee
Subtract all IDs found in the table from all available IDs. 从所有可用ID中减去表中找到的所有ID。 You create all available IDs by determining the number range first (
number(3)
ie 0 to 999 in your case) and then recursively create all numbers in that range. 首先确定数字范围(
number(3)
即0到999),然后再递归地创建该范围内的所有数字,即可创建所有可用的ID。
In standard SQL (and in Oracle as of version 11.2) you'd use a recursive CTE for this. 在标准SQL(以及从11.2版开始的Oracle中)中,您将为此使用递归CTE。
with all_ids(id) as
(
select power(10, data_precision) - 1 as id from all_tab_cols
where owner = 'HR' and table_name = 'EMPLOYEES' and column_name = 'EMPLOYEE_ID'
union all
select id - 1 from all_ids where id > 0
)
select id from all_ids
minus
select employee_id from employees;
I am assuming that your table consists some columns X,Column Y other than empl_no.So to find an available primary key you need to find the of rows which are NULL for column X and Y (that means they are empty).Below query might help.. 我假设您的表包含除empl_no之外的某些X,Column Y列。因此,要找到可用的主键,您需要查找X和Y列为NULL的行(这意味着它们为空)。救命..
SELECT empl_no FROM emplpyee WHERE columnX IS NULL and columnY IS NULL SELECT empl_no FROM emplpyee WHERE columnX IS NULL和columnY IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.