简体   繁体   English

sql查询表

[英]sql look up table

I have a table that contains institute names like the following: 我有一个包含研究所名称的表格,如下所示:

National high school Karachi
United school Islamabad
High school Kort Adu
Iqra school Muzafar abad

Karachi , Islamabad , Kort Adu and Muzafar abad are the names of cities. KarachiIslamabadKort AduMuzafar abad是城市的名称。

I will have a lookup table which will contain the above city names and will be limited to between 30 to 40 city names. 我将有一个查找表,其中包含上述城市名称,并且限于30至40个城市名称之间。

I am unable to write a query to search all city names with the aforementioned institute names and assign the city name in the city column of the first table, which contains the institute names. 我无法编写查询来搜索具有上述机构名称的所有城市名称,并在包含机构名称的第一张表的城市列中分配城市名称。

Like the following: 如下所示:

institute                           city
--------------------------------------------------
National high school Karachi        Karachi
United school Islamabad             Islamabad
United school Islamabad             Kort Adu
Iqra school Muzafar Abad            Muzafar Abad

Could someone please provide some much appreciated insight? 有人可以提供一些值得赞赏的见解吗?

Assuming you are using MySQL, you can do something like this: 假设您正在使用MySQL,则可以执行以下操作:

create table institute (institute varchar(100), city varchar(100));
insert into institute (institute) values 
('National high school Karachi'),
('United school Islamabad'),
('High school Kort Adu'),
('Iqra school Muzafar abad');

create table cities (cityname varchar(100));
insert into cities values ('Karachi'), ('Islamabad'), ('Kort Adu'), ('Muzafar abad'), ('Peshawar');

update institute i
inner join cities c on i.institute like concat('%', c.cityname)
set i.city = c.cityname;

Result: 结果:

select * from institute

|                    institute |         city |
|------------------------------|--------------|
| National high school Karachi |      Karachi |
|      United school Islamabad |    Islamabad |
|         High school Kort Adu |     Kort Adu |
|     Iqra school Muzafar abad | Muzafar abad |

Example: http://sqlfiddle.com/#!9/38bbc4/1 示例: http//sqlfiddle.com/#!9 / 38bbc4 / 1

If you were to use SQL Server, your update statement would change to 如果要使用SQL Server,则更新语句将更改为

update i
set i.city = c.cityname
from institute i
inner join cities c on i.institute like concat('%', c.cityname)

If you were to use PostgreSQL, your update statement would change to 如果您要使用PostgreSQL,则您的update语句将更改为

update institute i
set i.city = c.cityname
from cities c 
where i.institute like concat('%', c.cityname)

If you were to use Oracle (or even DB2 UDB), you update statement would change to 如果要使用Oracle(甚至DB2 UDB),则update语句将更改为

update institute i
set i.city = (select cityname from cities c where i.institute like concat('%', c.cityname))
where exists (select 1 from cities c where i.institute like concat('%', c.cityname));

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

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