I have 3 tables.
in pin code columns are entry id - number picode - number state - number district - number
pin code temp is same as master
city temp entry id - number city name - string state - number district - number state name - string
example data = pin code temp 32899, 343031, 29, 122
example data = city temp 6604, A Vellalapatti, 31, 666, Tamil Nadu
my problem is in some condition there are multiple entries available in city table with state and district.
I tried to get the city name using state and district. which gave multiple results. but my master table must have only one result per state. I know i have to use FIU dabase to get the actual data but the same issue in their list. multiple cities with same state and district.
You state:
pin code temp is same as master
and ask
how to actually figure out the query to select the accurate data and fill my master table
Ignore the city
table and use only the pin_code_temp
data to populate pin_code_master
.
For example, if you want to insert all the rows from pin_code_temp
into pin_code_master
that have new primary key values then:
INSERT INTO pin_code_master (id, picode, state, district)
SELECT id, picode, state, district
FROM pin_code_temp t
WHERE NOT EXISTS (
SELECT 1
FROM pin_code_master m
WHERE t.id = m.id -- Compare primary key columns
-- If you have different primary/unique keys then
-- change the filter and compare those columns.
)
Which, for the sample data:
CREATE TABLE city (
id NUMERIC(10) PRIMARY KEY,
city_name VARCHAR(50),
state NUMERIC(10),
district NUMERIC(10)
);
CREATE TABLE pin_code_master (
id NUMERIC(10) PRIMARY KEY,
picode NUMERIC(10),
state NUMERIC(10),
district NUMERIC(10)
);
CREATE TABLE pin_code_temp (
id NUMERIC(10) PRIMARY KEY,
picode NUMERIC(10),
state NUMERIC(10),
district NUMERIC(10)
);
INSERT INTO pin_code_master (id, picode, state, district)
SELECT 1, 1, 1, 1 FROM DUAL UNION ALL
SELECT 4, 3, 2, 2 FROM DUAL
INSERT INTO pin_code_temp (id, picode, state, district)
SELECT 1, 1, 1, 1 FROM DUAL UNION ALL
SELECT 2, 2, 1, 2 FROM DUAL UNION ALL
SELECT 3, 1, 2, 1 FROM DUAL UNION ALL
SELECT 4, 3, 2, 2 FROM DUAL
Then, after the INSERT
, pin_code_master
contains:
ID | PICODE | STATE | DISTRICT |
---|---|---|---|
1 | 1 | 1 | 1 |
4 | 3 | 2 | 2 |
2 | 2 | 1 | 2 |
3 | 1 | 2 | 1 |