[英]find missing varchar primary keys
I am going over my database and I wanted to know how many primary keys are missing from my tables. 我正在浏览我的数据库,我想知道我的表中缺少了多少主键。 Now sometime I have only one primary key which is integer, which is easy, I looked at this SQL: find missing IDs in a table but it was for numeric column.
现在有时我只有一个主键是整数,这很容易,我看了这个SQL:在表中查找缺少的ID,但它是用于数字列。
I got the below solution from SO itself and it helps in case the PK was integer. 我从SO本身得到了以下解决方案,它有助于PK是整数。 selecting only the PK into a file I awk through it to find the next missing sequence
只选择PK到文件中我通过它来查找下一个丢失的序列
gawk '$1!=p+1{print p+1}{p=$1}'
Now My question revolves around the varchar Primary keys. 现在我的问题围绕着varchar主键。 like a Order reference number perhaps which is not a sequentially increasing integer but a string/varchar/alphanumeric column has anybody tried this already.
就像一个订单参考号或许不是一个顺序增加的整数但是一个字符串/ varchar / alphanumeric列有任何人已经尝试过这个。 (a value like A123Z43), in integer/numeric it was easy, I add 1 and I get the next sequence.
(像A123Z43这样的值),在整数/数字中很容易,我加1,然后我得到下一个序列。
I am not sure but it just struck me, would the hash of one key and the next have anything to do with it. 我不确定,但它只是打动了我,一把钥匙和下一把钥匙的散列是否与它有关。 I will see if I can try that.
我会看看我是否可以尝试。
this will get more complex if i got two columns as Primary Keys one being numeric and the other being varchar. 如果我有两列作为主键,一个是数字,另一个是varchar,这将变得更复杂。
I am working with SQL server and Postgres at the moment. 我目前正在使用SQL Server和Postgres。
you were checking not missing PK values, but rather sequence gaps. 你检查的是没有丢失PK值,而是序列间隙。 In case of PK on text - only you can define rule for default value.
如果是文本PK,则只能为默认值定义规则。 If you have no default value for PK column, you can't check gaps.
如果PK列没有默认值,则无法检查间隙。 Eg you have two values in PK: "C12" and "$D" - so what you miss here?.. Does it start from literal?
例如,你在PK中有两个值:“C12”和“$ D” - 所以你在这里错过了什么?..它是从文字开始的吗? from digit?
从数字? are spaces allowed?
允许的空间? and so on.
等等。
Now if you have some sort of rule defined, you can generate_serie and then join it - checking for gaps. 现在,如果你定义了某种规则,你可以使用generate_serie然后加入它 - 检查间隙。 eg:
例如:
t=# select chr(g)||n,pk from generate_series(65,100,1) g join generate_series(1,9,1) n on true left outer join (values ('A4'),('B3')) as v (pk) on pk=chr(g)||n limit 19;
?column? | pk
----------+----
A1 |
A2 |
A3 |
A4 | A4
A5 |
A6 |
A7 |
A8 |
A9 |
B1 |
B2 |
B3 | B3
B4 |
B5 |
B6 |
B7 |
B8 |
B9 |
C1 |
(19 rows)
Time: 0.392 ms
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.