473,406 Members | 2,620 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Constraints to Guarantee unique across tables with foreign key?

I have two tables like following:

create table attendancereport (
id serial unique not null,
staff_id integer not null references staff(id),
schoolyear varchar not null references schoolyear(year),
students_id integer not null references students(id)
);

// schoolyear.year in format "2003 - 2004".

Create table attendancerecords (
attendancereport_id integer not null references attendancereport(id),
schoolday integer not null references schooldays(day),
attended bool not null
);

// schoolday.day in formation YYYYMMDD as in 200301222 for dec 22, 2003.

What I'm looking for is a way to create a unique( ) across tables via the
foriegn key, something like

Alter table attendancerecords
ADD unique (schoolday, attendancereport.students_id);

so that for a given student, there can be one and only one of any particular
schoolday. Can this be done with constraints?

-Ben

--
"I kept looking around for somebody to solve the problem.
Then I realized I am somebody"
-Anonymous
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

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

Nov 23 '05 #1
2 2994
Am Donnerstag, 26. August 2004 04:43 schrieb Benjamin Smith:
I have two tables like following:

create table attendancereport (
id serial unique not null,
staff_id integer not null references staff(id),
schoolyear varchar not null references schoolyear(year),
students_id integer not null references students(id)
);

// schoolyear.year in format "2003 - 2004".

Create table attendancerecords (
attendancereport_id integer not null references attendancereport(id),
schoolday integer not null references schooldays(day),
attended bool not null
);

// schoolday.day in formation YYYYMMDD as in 200301222 for dec 22, 2003.

What I'm looking for is a way to create a unique( ) across tables via the
foriegn key, something like

Alter table attendancerecords
ADD unique (schoolday, attendancereport.students_id);


You need mutliple column foreign keys like this (didnt test it just typed and
its early in the morning, havn't got any coffee yet):

CREATE TABLE attendancereport (
students_id integer NOT NULL REFERENCES students(id),
schoolyear varchar NOT NULL REFERENCES schoolyear(year),
staff_id integer NOT NULL REFERENCES staff(id),
CONSTRAINT pk_arep PRIMARY KEY (students_id, schoolyear)
);

CREATE TABLE attendancerecords (
students_id integer NOT NULL,
schoolyear varchar NOT NULL,
schoolday integer NOT NULL REFERENCES schooldays(day),
attended boolean NOT NULL,
CONSTRAINT pk_arec PRIMARY KEY (students_id, schoolyear, schoolday),
CONSTRAINT fk_students_id FOREIGN KEY (students_id, schoolyear)
REFERENCES attendancereport(students_id, schoolyear)
);

this way you can have only ONE unique record for each student on each day of
any schoolyear. The Uniqueness is guranteed by the Primary key (which is in
theory nothing else like a uniquey key which is NOT NULL)

I dropped the serial columns because i dont know what those surrogate keys are
for, but you can add them again, if you want to select records by number
within your application.

[Maybe you could even place the staff_id field into your students table and
drop the table attendancereport.]

kind regards,
janning

---------------------------(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 23 '05 #2
Thanks!

Using the dual foreign key essentially allows me to "import" the students_id
field from attendancereports into attendancerecords, thereby satisfying my
requirement to guarantee uniqueness, even though students_id is really more
applicable to the attendancereports table.

(I can't drop attendancereports table for the reason that the report itself
needs to be tracked in order to be sure all forms have been turned in and
signed - I did not mention additional fields to guarantee that the form has
been verified by another staff member, and is thus "on file".)

I started SQL (as do many) with MySQL, and very quickly became frustrated with
its limitations. I moved to PG, and now, even after developing dozens of
applications over the ensuing half decade, am continuously amazed by the fact
that whatever problem I run into, Postgres can handle it.

Damn nice software....

-Ben

On Thursday 26 August 2004 01:15, Janning Vygen wrote:
Am Donnerstag, 26. August 2004 04:43 schrieb Benjamin Smith:
I have two tables like following:

create table attendancereport (
id serial unique not null,
staff_id integer not null references staff(id),
schoolyear varchar not null references schoolyear(year),
students_id integer not null references students(id)
);

// schoolyear.year in format "2003 - 2004".

Create table attendancerecords (
attendancereport_id integer not null references attendancereport(id),
schoolday integer not null references schooldays(day),
attended bool not null
);

// schoolday.day in formation YYYYMMDD as in 200301222 for dec 22, 2003.

What I'm looking for is a way to create a unique( ) across tables via the
foriegn key, something like

Alter table attendancerecords
ADD unique (schoolday, attendancereport.students_id);
You need mutliple column foreign keys like this (didnt test it just typed

and its early in the morning, havn't got any coffee yet):

CREATE TABLE attendancereport (
students_id integer NOT NULL REFERENCES students(id),
schoolyear varchar NOT NULL REFERENCES schoolyear(year),
staff_id integer NOT NULL REFERENCES staff(id),
CONSTRAINT pk_arep PRIMARY KEY (students_id, schoolyear)
);

CREATE TABLE attendancerecords (
students_id integer NOT NULL,
schoolyear varchar NOT NULL,
schoolday integer NOT NULL REFERENCES schooldays(day),
attended boolean NOT NULL,
CONSTRAINT pk_arec PRIMARY KEY (students_id, schoolyear, schoolday),
CONSTRAINT fk_students_id FOREIGN KEY (students_id, schoolyear)
REFERENCES attendancereport(students_id, schoolyear)
);

this way you can have only ONE unique record for each student on each day of
any schoolyear. The Uniqueness is guranteed by the Primary key (which is in
theory nothing else like a uniquey key which is NOT NULL)

I dropped the serial columns because i dont know what those surrogate keys are for, but you can add them again, if you want to select records by number
within your application.

[Maybe you could even place the staff_id field into your students table and
drop the table attendancereport.]

kind regards,
janning


--
"I kept looking around for somebody to solve the problem.
Then I realized I am somebody"
-Anonymous
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

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

Nov 23 '05 #3

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

Similar topics

0
by: Rajesh Kapur | last post by:
We use InnoDB tables and foreign key constraints extensively. The mysqldump backs up the database tables in alphabetical order with foreign key constraints defined in the create statement of each...
6
by: Brian Basquille | last post by:
Just started learning SQL recently. But one thing i'm still not clear on is about altering relationships between tables after they've been created. Instead of creating a foreign key when the...
13
by: Bob Stearns | last post by:
Why is the following constraint invalid? I want to make sure that every row in IS3.ANIMALS_PRIV_INDEXES matches one of those in IS3.table_var_defn with part of the primary key fixed. Since this is...
2
by: Christopher Weaver | last post by:
I'm trying to insert a new Row within an existing Table within an existing DataSet using the following: DataRow NewTaskRow = dsTaskActivities.Tables.NewRow();...
8
by: wespvp | last post by:
I am using PostgreSQL 7.4.1 on RedHat 7.2. The query I am executing is something like (I replaced all the return values with 'count'): db=> explain select count(*) from messages m join (select...
3
by: David Parker | last post by:
I would like to be able to truncate all of the tables in a schema without worrying about FK constraints. I tried issuing a "SET CONSTRAINTS ALL DEFERRED" before truncating, but I still get constraint...
6
by: Emin | last post by:
Dear Experts, When I use a single table I can easily use constraints to enforce my business logic, but what do I do when I normalize a single table into multiple tables. For example, imagine...
4
by: Adrock952 | last post by:
I am trying to create my tables where if i delete/update a record from one table, all the other tables are affected by deleting/updating any records that reference the original record. For...
4
by: Bobby Edward | last post by:
I have an xsd dataset. I created a simple query called GetDataByUserId. I can preview the data fine! I created a very simple BLL function that calls it and returns a datatable. When I run...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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...
0
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...

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.