473,748 Members | 7,571 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dumbheaded SQL question (probably join or subselect) - longish

Dear all,

for some reason I just cannot get my brain wrapped around the
required syntax for the following. I think I need to either
use a join or subselect(s):

Situation:
----------
I have two tables (simplified here) for an international
medical office application (www.gnumed.org):

create table city (
id serial primary key,
postcode text,
name text
);

create table street (
id serial primary key,
id_city integer references city(id),
postcode text,
name text
);

Yes, postcode is in both tables by design:

e.g. in Germany postcodes can be valid for:
- several smaller "towns"
- one "town"
- several streets in one "town"
- one street in one "town"
- part of one street in one "town"

Problem:
--------
I want to create a view v_zip2data that lists:

- all zip codes from "street" with associated data
- all those zip codes in "city" that are not in "street" OR
that belong to a different city name in "street"
- and from both tables only those rows that do have a zip code

insert into city (id, postcode, name) values (1, '02999', 'Gross Saerchen');
insert into city (id, postcode, name) values (2, '02999', 'Lohsa');
insert into city (id, postcode, name) values (3, '04318', 'Leipzig');
insert into city (id, postcode, name) valueus (4, '06686, 'Luetzen');
insert into city (id, name) values (5, 'Leipzig');

insert into street (id_city, name) values (1, 'No-ZIP street');
insert into street (id_city, postcode, name) values (2, '02999', 'Main Street');
insert into street (id_city, postcode, name) values (3, '04217', 'Riebeckstrasse ');
insert into street (id_city, postcode, name) values (5, '04318', 'Zum Kleingartenpark ');
insert into street (id_city, postcode, name) values (6, '04318', 'Wurzener Strasse');

I want to see in the view:

(from street)
02999, Main Street, Lohsa
04217, Riebeckstrasse, Leipzig
- city.postcode ignored and overridden
04318, Zum Kleingartenpark , Leipzig
04318, Wurzener Strasse, Leipzig
- same zip/city but different street
(from city)
02999, NULL, Gross Saerchen
- zip is in "street" but points to city "Lohsa"
06686, NULL, Luetzen
- zip not listed in "street"

I want to exclude from the view:
- city.id=2 since that is covered by the second "street" row
- city.id=3 since that is covered by the fourth "street" row
- city.id=5 since that does not have a zip code
- first row in "street" since it does not have a zip code

I have been trying to join city and street on "city.postc ode <>
street.postcode " in various ways but was unable to achieve the
view I wanted. Same with using subselects in the where clause
(NOT IN ... which is supposed to be of suboptimal performance
IIRC). A first step would be to have a view listing all zips
from "city" that satisfy:

- not listed in "street" OR
- listed in "street" but street.id_city points to a different city

Any help would be appreciated.

Thanks,
Karsten Hilbert, MD
--
GPG key ID E4071346 @ wwwkeys.pgp.net
E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 11 '05 #1
2 2037
Karsten Hilbert wrote:
Dear all,

for some reason I just cannot get my brain wrapped around the
required syntax for the following. I think I need to either
use a join or subselect(s):

Situation:
----------
I have two tables (simplified here) for an international
medical office application (www.gnumed.org):

create table city (
id serial primary key,
postcode text,
name text
);

create table street (
id serial primary key,
id_city integer references city(id),
postcode text,
name text
);

Yes, postcode is in both tables by design:

e.g. in Germany postcodes can be valid for:
- several smaller "towns"
- one "town"
- several streets in one "town"
- one street in one "town"
- part of one street in one "town"

Problem:
--------
I want to create a view v_zip2data that lists:

- all zip codes from "street" with associated data
- all those zip codes in "city" that are not in "street" OR
that belong to a different city name in "street"
- and from both tables only those rows that do have a zip code

insert into city (id, postcode, name) values (1, '02999', 'Gross Saerchen');
insert into city (id, postcode, name) values (2, '02999', 'Lohsa');
insert into city (id, postcode, name) values (3, '04318', 'Leipzig');
insert into city (id, postcode, name) valueus (4, '06686, 'Luetzen');
insert into city (id, name) values (5, 'Leipzig');

insert into street (id_city, name) values (1, 'No-ZIP street');
insert into street (id_city, postcode, name) values (2, '02999', 'Main Street');
insert into street (id_city, postcode, name) values (3, '04217', 'Riebeckstrasse ');
insert into street (id_city, postcode, name) values (5, '04318', 'Zum Kleingartenpark ');
insert into street (id_city, postcode, name) values (6, '04318', 'Wurzener Strasse');

I want to see in the view:

(from street)
02999, Main Street, Lohsa
1:

SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode = street.postcode
04217, Riebeckstrasse, Leipzig
- city.postcode ignored and overridden
2:

SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode <> street.postcode
04318, Zum Kleingartenpark , Leipzig
3:

SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode IS NULL
04318, Wurzener Strasse, Leipzig
- same zip/city but different street
4:

SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.postcode = street.postcode AND
NOT EXISTS (
SELECT 1
FROM city c
WHERE street.id_city = c.id
)
(from city) 02999, NULL, Gross Saerchen
- zip is in "street" but points to city "Lohsa"
5:

SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.id = street.id_city AND
city.postcode = street.postcode AND
) AND
city.postcode IS NOT NULL
06686, NULL, Luetzen
- zip not listed in "street"
6:

SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.postcode = street.postcode
)
city.postcode IS NOT NULL

----

Now, all you need to do is unionize these selects:

CREATE VIEW v_zip2data AS
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode = street.postcode
UNION
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode <> street.postcode
UNION
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city AND
city.postcode IS NULL
UNION
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.postcode = street.postcode AND
NOT EXISTS (
SELECT 1
FROM city c
WHERE street.id_city = c.id
)
UNION
SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.id = street.id_city AND
city.postcode = street.postcode AND
) AND
city.postcode IS NOT NULL
UNION
SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.postcode = street.postcode
) AND
city.postcode IS NOT NULL;

Please verify each of the selects that compose the view. The UNION
will eliminate any redundancies, so some of the SELECTs may be able to
be logically combined:

1, 2 and 3 appear to be, logically:

SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city

5 and 6 appear to be, logically:

SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.id = street.id_city
) AND
city.postcode IS NOT NULL;

so that reduces the view definition to:

CREATE VIEW v_zip2data AS
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.id = street.id_city
UNION
SELECT street.postcode , street.name, city.name
FROM city, street
WHERE city.postcode = street.postcode AND
NOT EXISTS (
SELECT 1
FROM city c
WHERE street.id_city = c.id
)
SELECT city.postcode, NULL, city.name
FROM city
WHERE NOT EXISTS (
SELECT 1
FROM street
WHERE city.id = street.id_city
) AND
city.postcode IS NOT NULL;
Any help would be appreciated.

Thanks,
Karsten Hilbert, MD


Of course, I could (easily) be misunderstandin g the nature of the
data, but it should be a starting point. If you consider normalizing
further, here's a good paper to aid you on the restructuring: ;-)

http://home.earthlink.net/~billkent/Doc/simple5.htm

HTH,

Mike Mascari
ma*****@mascari .com




---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 11 '05 #2
UNION. Duh. I knew why I wrote to this list :-)

Thanks Mike.

Karsten
--
GPG key ID E4071346 @ wwwkeys.pgp.net
E167 67FD A291 2BEA 73BD 4537 78B9 A9F9 E407 1346

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 11 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
6409
by: Chris Greening | last post by:
I'm seeing a very strange problem with outer joins. The example below replicates the problem: create table data1 (dim1 integer, stat1 float); create table data2 (dim1 integer, stat2 float); insert into data1 values (1,1); insert into data1 values (1,2); insert into data1 values (2,2);
0
1440
by: John Larsen | last post by:
Does anybody know if there is a way to aggregate a table then join it to another table? I assume this would be possible with a subquery as in SELECT * FROM t1 WHERE t1.a=(SELECT sum(t2.b) FROM t2 group by t2.c); Except when I do it with 4.1alpha I get error " ERROR 1240: Subselect returns more than 1 record" I though that was the whole point of a subselect is that you got more than 1 record
6
4798
by: Dave | last post by:
To build a grid, all the distinct rows from T1 are required, and only those from T2 which fall btn 2003-09-11 and 2003-09-18. In the following example: A is included because it is within the date range C is inclucded because the date is null B is excluded because it is outside the date range Any suggestions on how to get the desired result would be greatly appreciaed!
2
3043
by: kjc | last post by:
Not sure if this is the right group to post this to but. This is the current query that I have. select tableA.id,tableB.artist,tableB.image,from tableA,tableB where tableA.image = tableB.image AND tableB.price >0 AND tableB.price < 20 order by tableB.price DESC' What I need is, for each row returned I need information from a third and fourth table. tableC, and tableD.
1
1560
by: Tom Schindl | last post by:
Hi, maybe I'm simply to dump but I could not transform this SQL-Statment which uses a Sub-select and create on that uses an OUTER JOIN. --------------------------8<-------------------------- SELECT p_id, CONCAT( " hist. ", CONCAT( UPPER(p_surname), CONCAT( ',', p_givenname ) ) )
5
8215
by: Todd | last post by:
Data related to the query I'm working on is structured such that TableA and TableB are 1-many(optional). If an item on TableA has children on TableB, I need to use the Max(tstamp) from Table B in a condition, otherwise I need to use a tstamp from TableA (note:there are additional tables and conditions for this query, but this problem is based around these 2). I attempted having TableB (as B) "left outer joined" to TableA, and a condition...
2
7356
by: Morten K. Poulsen | last post by:
(re-post) Dear list, Please let me know if this is not the list to ask this kind of question. I am trying to optimize a query that joins two relatively large (750000 rows in each) tables. If I do it using a subselect, I can "force" the planner to choose the fastest path. Now, my question is:
4
23947
by: johnfaulkner | last post by:
Hi, I am trying to perform a single select of data from 2 tables, table A and table B. Table B may have none, one or many corresponding rows. If table B has no corresponding rows then table B values should be set to null. If table B has one or more corresponding rows then table B values should be set to the corresponding table B row with the lowest DATE. I think I should do a left outer join on table A and table B but can't work out...
2
2250
by: frederikengelen | last post by:
Hello all, We are seeing strange behaviour for queries on a table we need to convert data from. We try to find out whether table A(B_CONV_ID) contains data that does not exists in table B(CONV_ID). We expect that there is data missing in table B, thus finding a positive number of records. There are two tables, A and B.
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9544
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9324
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3313
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.