简体   繁体   English

字符串的匹配返回 SQL 中另一个表的结果

[英]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 ...这应该相当容易,但我仍然从 SQL 开始,所以......

I have a table of mobile phone numbers ( mobilephones ) like this:我有一个像这样的手机号码表( mobilephones ):

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.因此,虽然 221 可能同时表示柏林和魏斯巴登,但状态键表示哪个是。 97+221 = Weisbaden and 09+221 = Berlin. 97+221 = 魏斯巴登,09+221 = 柏林。 For check this, I have the table base :为了检查这个,我有表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.我有第三个表(````mobilecity```),它是 mobile_number 和城市。 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.基本上我需要用电话号码跨越州和城市列,并返回电话号码和城市。

You can use join .您可以使用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) .这看起来更复杂,但它可能会使用base(state_number, mobile_number)上的索引。

You can populate the table with INSERT INTO...SELECT :您可以使用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 |

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

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