你可能想嘗試以下(使用MySQL的INSTR()
和LENGTH()
功能):
SELECT (SELECT prefix
FROM numbers n2
WHERE INSTR(n1.prefix, n2.prefix) = 1
ORDER BY LENGTH(n2.prefix)
LIMIT 1
) AS significant,
n1.prefix
FROM numbers n1;
退房@onedaywhen's answer對於上述的ANSI SQL版本查詢。
測試用例:
CREATE TABLE numbers (prefix int);
INSERT INTO numbers VALUES (542);
INSERT INTO numbers VALUES (54299);
INSERT INTO numbers VALUES (374);
INSERT INTO numbers VALUES (37477);
INSERT INTO numbers VALUES (37493);
INSERT INTO numbers VALUES (37494);
INSERT INTO numbers VALUES (37498);
INSERT INTO numbers VALUES (37447);
INSERT INTO numbers VALUES (37455);
INSERT INTO numbers VALUES (3749);
INSERT INTO numbers VALUES (37410);
INSERT INTO numbers VALUES (297);
INSERT INTO numbers VALUES (29756);
INSERT INTO numbers VALUES (29759);
INSERT INTO numbers VALUES (29766);
INSERT INTO numbers VALUES (29769);
INSERT INTO numbers VALUES (29796);
INSERT INTO numbers VALUES (29799);
INSERT INTO numbers VALUES (29773);
INSERT INTO numbers VALUES (29774);
INSERT INTO numbers VALUES (297600);
INSERT INTO numbers VALUES (297622);
INSERT INTO numbers VALUES (247);
INSERT INTO numbers VALUES (61);
INSERT INTO numbers VALUES (61861);
INSERT INTO numbers VALUES (61862);
INSERT INTO numbers VALUES (61863);
結果:
+-------------+--------+
| significant | prefix |
+-------------+--------+
| 542 | 542 |
| 542 | 54299 |
| 374 | 374 |
| 374 | 37477 |
| 374 | 37493 |
| 374 | 37494 |
| 374 | 37498 |
| 374 | 37447 |
| 374 | 37455 |
| 374 | 3749 |
| 374 | 37410 |
| 297 | 297 |
| 297 | 29756 |
| 297 | 29759 |
| 297 | 29766 |
| 297 | 29769 |
| 297 | 29796 |
| 297 | 29799 |
| 297 | 29773 |
| 297 | 29774 |
| 297 | 297600 |
| 297 | 297622 |
| 247 | 247 |
| 61 | 61 |
| 61 | 61861 |
| 61 | 61862 |
| 61 | 61863 |
+-------------+--------+
27 rows in set (0.00 sec)
應該,即使你使用的是varchar
來存儲數字工作。
UPDATE:
至於性能,你可能要考慮你的表緩存significant
部分:
CREATE TABLE numbers (prefix int, significant int);
-- Fill in the prefixes, leaving the significant field as NULL.
然後,你可以生成significant
場如下(使用MySQL):
UPDATE numbers n
JOIN (SELECT (SELECT prefix
FROM numbers n2
WHERE INSTR(n1.prefix, n2.prefix) = 1
ORDER BY LENGTH(n2.prefix)
LIMIT 1
) AS significant,
n1.prefix
FROM numbers n1
) s ON (s.prefix = n.prefix)
SET n.significant = s.significant;
SELECT * FROM numbers;
+--------+-------------+
| prefix | significant |
+--------+-------------+
| 542 | 542 |
| 54299 | 542 |
| 374 | 374 |
| 37477 | 374 |
| 37493 | 374 |
| 37494 | 374 |
...
無論何時在numbers
表中添加新行,您都可能想要運行UPDATE
查詢。
應該如何MySQL的知道什麼是重要的數字,什麼是前綴?每個有效數字總是最大3位數? – Konerak 2010-06-23 09:23:03
因此,對於每個'前綴'值'p',它的'significant'是'p'開頭的最短'前綴'? – AakashM 2010-06-23 09:24:33
@AakashM - 正確的 – veccy 2010-06-23 09:30:29