zohaibkhan
zohaibkhan

Reputation: 71

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.

I will have a lookup table which will contain the above city names and will be limited to between 30 to 40 city names.

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?

Upvotes: 1

Views: 108

Answers (1)

zedfoxus
zedfoxus

Reputation: 37029

Assuming you are using MySQL, you can do something like this:

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

If you were to use SQL Server, your update statement would change to

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

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

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

Upvotes: 2

Related Questions