sql查找表

时间:2015-12-19 18:41:29

标签: sql database

我有一个包含机构名称的表格,如下所示:

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

KarachiIslamabadKort AduMuzafar abad是城市的名称。

我将有一个包含上述城市名称的查找表,并且将限制在30到40个城市名称之间。

我无法编写查询来搜索具有上述学院名称的所有城市名称,并在第一个表的城市列中分配城市名称,其中包含学院名称。

如下所示:

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

有人可以提供一些非常感激的见解吗?

1 个答案:

答案 0 :(得分:2)

假设您使用的是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;

结果:

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 |

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

如果您要使用SQL Server,则更新语句将更改为

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

如果您使用PostgreSQL,您的更新语句将更改为

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

如果您要使用Oracle(甚至是DB2 UDB),则更新语句将更改为

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));