简体   繁体   中英

Update field with query using longest match number

I have the following table of call_logs:

+------------+---------------------+------------+-------------+--------------+
| id         | datetime            | a_number   | b_number    |     nem      |
+------------+---------------------+------------+-------------+--------------+
| 1262662410 | 2020-07-17 10:43:57 | 3415529238 | 12642356719 |              |
| 1262661229 | 2020-07-17 10:43:48 | 1126751251 | 12641344559 |              |
| 1262658679 | 2020-07-17 10:43:28 | 3516807236 | 16199573103 |              |
+------------+---------------------+------------+-------------+--------------+

and another table of prefixes:

+---------+-------+-------------------+------+
| prefix  | lenght| description       | nem  |
+---------+-------+-------------------+------+
| 1907    |     4 | ALASKA            | ALAS |
| 1684    |     4 | AMERICAN SAMOA    | ASAM |
| 1264    |     4 | ANGUILLA          | AGLL |
| 1264235 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264469 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264476 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264536 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264537 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264538 |     7 | ANGUILLA - MOBILE | AGLM |
| 1264539 |     7 | ANGUILLA - MOBILE | AGLM |
+---------+-------+-------------------+------+

What MySQL query or precedure do you recommend to update the call_logs.nem field analyzing the prefixes.prefix field that best matches (with the greatest number of digits) with the field call_logs.b_number .

Example:

+------------+---------------------+------------+-------------+--------------+
| id         | datetime            | a_number   | b_number    |     nem      |
+------------+---------------------+------------+-------------+--------------+
| 1262662410 | 2020-07-17 10:43:57 | 3415529238 | 12642356719 |    AGLM      |
| 1262661229 | 2020-07-17 10:43:48 | 1126751251 | 12641344559 |    AGLL      |
+------------+---------------------+------------+-------------+--------------+

call_logs is a big table, it would be good to find the most efficient method. Can anyone help me on this? Thanks a lot!

CLARIFICATION: Both fields: b_number and prefix are VARCHAR type. What type of UPDATE Query could be done in this case?

You can use not exists . Assuming that number and prefix are of numeric datatypes:

update call_logs c
inner join prefixes p on (c.b_number / p.prefix) % 10 = 0
set c.mem = p.mem
where not exists (
    select 1
    from prefixes p1
    where (c.b_number / p1.prefix) % 10 = 0 and p1.length > p.length
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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