简体   繁体   English

在SQL查询中选择对编号

[英]Select pair numbers in SQL Query

Database: 数据库:

+------------+
|   Number   |
+------------+
| 0050000235 |
+------------+
| 5532003644 |
+------------+
| 1122330505 |
+------------+
| 1103220311 |
+------------+
| 1103000011 |
+------------+
| 1103020012 |
+------------+

To select numbers having pair of "0" 3 times I tried: 要选择3对具有“ 0”对的数字,我尝试过:

SELECT * FROM numbers
WHERE Number LIKE "%00%00%00%"
    OR Number LIKE "%00%0000%"
    OR Number LIKE "%0000%00%"
    OR Number LIKE "0000%00%"
    OR Number LIKE "%00%0000"   
    OR Number LIKE "00%0000%"
    OR Number LIKE "%0000%00"
    OR Number LIKE "%0000%00"
    OR Number LIKE "%000000%" 
    OR Number LIKE "000000%"
    OR Number LIKE "%000000" 

This results me: 这导致我:

0050000235 0050000235

But the way I am using, I think it's not a clean method. 但是我使用的方式不是很干净的方法。

Question How to fetch numbers having 3 pairs in it with clean SQL query? 问题如何使用干净的SQL查询获取其中有3对数字?

The result will be: 结果将是:

0050000235, 5532003644, 1122330505, 1103220311 & 1103000011 0050000235、5532003644、1122330505、1103220311和1103000011

Create a series of numbers from 0 to 9 with UNION ALL and cross join to the table. 使用UNION ALL创建从0到9的一系列数字,然后交叉连接到表。
Each of these numbers will be doubled and replaced in the column of the table with an empty string. 这些数字中的每个数字都会加倍,并在表的列中替换为空字符串。 The difference in length of each replacement will be summed and if it is greater than 6 this means that there exist at least 3 pairs: 每次替换的长度差将相加,如果大于6,则表示至少存在3对:

select 
  n.number
from (
  select 0 d union all select 1 d union all select 2  union all 
  select 3 union all select 4 union all select 5 union all 
  select 6 union all select 7 union all select 8 union all select 9
) s cross join numbers n
group by n.number                     
having sum(
  length(n.number) - length(replace(n.number, repeat(d, 2), '')) 
) >= 6 

See the demo . 参见演示
Results: 结果:

| number     |
| ---------- |
| 0050000235 |
| 1103000011 |
| 1103220311 |
| 1122330505 |
| 5532003644 |
where Number rlike '((00|11|22|33|44|55|66|77|88|99).*){3}'

How about using regular expressions? 使用正则表达式如何?

where number regexp '00.*00.*00'

Or slightly shorter: 或稍短:

where number regexp '(00.*){3}'

You can readily generalize this to any two numbers: 您可以轻松地将其概括为任意两个数字:

where number regexp '([0-9]{2}.*){3}'

If you want to ensure exactly six '0' (as opposed to more): 如果要确保恰好六个'0' (而不是更多):

where number regexp '^[^0]*00[^0]*00[^0]*00[^0]*$'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM