Remo
Remo

Reputation: 51

Match of a string returns a result from another table in SQL

This should be reasonably easy, but I'm still starting with SQL, so ...

I have a table of mobile phone numbers (mobilephones) like this:

mobile_number
------------
1406-09-227
1206-09-221
1104-97-221
1507-92-329

The final digits of the mobile number indicates me the state and the city. Each city is a combination of a city key plus a state key. Thus, while 221 may indicate both Berlin and Weisbaden, it is the state key that indicates which is. 97+221 = Weisbaden and 09+221 = Berlin. For check this, I have the table base:

state_number | city_number| state | city    
-------------|------------|-------|---------
09           | 227        | Hesse | Frankfurt
09           | 221        | Hesse | Weisbaden
97           | 221        | Berlin| Berlin
92           | 329        | Sarre | Saarbrücken 

Right. I have a third table (````mobilecity```) which is the mobile_number and the city. This is where I start to have problems. This table is a result of the previous two. I hope it goes like this:

mobile_number | city
--------------|------
1406-09-227   | Frankfurt
1206-09-221   | Weisbaden
1104-97-221   | Berlin
1507-92-329   | Saarbrücken

I have no idea how to get started. Basically I need to cross the state and city columns with the phone number and return the phone number and the city.

Upvotes: 0

Views: 45

Answers (2)

forpas
forpas

Reputation: 164099

You can populate the table with INSERT INTO...SELECT:

insert into mobilecity(mobile_number, city)
select m.mobile_number, b.city
from mobilephones m left join base b
on concat(b.state_number, '-', b.city_number) = right(m.mobile_number, 6);

See the demo.
Results:

| mobile_number | city        |
| ------------- | ----------- |
| 1406-09-227   | Frankfurt   |
| 1206-09-221   | Weisbaden   |
| 1104-97-221   | Berlin      |
| 1507-92-329   | Saarbrücken |

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269953

You can use join. Here is one method:

select mp.*, b.*
from mobilephones mp left join
     base b
     on mp.mobile_number like concat('%-', b.state_number, '-', b.city_number);

Alternatively, you can phrase this as:

select mp.*, b.*
from mobilephones mp left join
     base b
     on substring_index(substring_index(mp.mobile_number, '-', -2), '-', 1) = b.state_number and
        substring_index(mp.mobile_number, '-', -1) =  b.city_number;

This looks more complicated, but it might make use of an index on base(state_number, mobile_number).

Upvotes: 1

Related Questions