Ken Wong Software Development Blog

July 1, 2007

No Duplicate Keys in Foreign Key Tables

Filed under: Question And Answer, SQL — canonw @ 8:44 pm

Background

We have these tables with constrained relationship.

-- DROP TABLE FKeyTable3
-- DROP TABLE FKeyTable3
-- DROP TABLE FKeyTable1
-- DROP TABLE KeyTable
CREATE TABLE KeyTable (
  KeyColumn nvarchar(2) NOT NULL
)
ALTER TABLE KeyTable
  ADD CONSTRAINT PK_KeyTable
  PRIMARY KEY (KeyColumn)

CREATE TABLE FKeyTable1 (
  KeyColumn nvarchar(2) NOT NULL,
  ValueColumn nvarchar(13)
)
ALTER TABLE FKeyTable1
  ADD CONSTRAINT FK_FKeyTable1
  FOREIGN KEY (KeyColumn) REFERENCES KeyTable(KeyColumn)

CREATE TABLE FKeyTable2 (
  KeyColumn nvarchar(2) NOT NULL,
  ValueColumn nvarchar(13)
)
ALTER TABLE FKeyTable2
  ADD CONSTRAINT FK_FKeyTable2
  FOREIGN KEY (KeyColumn) REFERENCES KeyTable(KeyColumn)

CREATE TABLE FKeyTable3 (
  KeyColumn nvarchar(2) NOT NULL,
  ValueColumn nvarchar(13)
)
ALTER TABLE FKeyTable3
  ADD CONSTRAINT FK_FKeyTable3
  FOREIGN KEY (KeyColumn) REFERENCES KeyTable(KeyColumn)
KeyColumn
BL
BM
CA
CI
CL
CS
CV

Issue

I would like to add a requirement to these tables. The KeyColumn in KeyTable should list either zero or one time in its foreign key table. e.g. if FKeyTable1 has ‘CI’ KeyColumn value, the ‘CI’ cannot be found in table FKeyTable2 and in table FKeyTable3.

Question

Write a SQL that list all the KeyColumn value violating the one of zero time entry rule.

Answer

SELECT  COUNT(KeyColumn) as KeyCount, KeyColumn
FROM (SELECT KeyColumn FROM FKeyTable1
         UNION ALL SELECT KeyColumn FROM FKeyTable2
         UNION ALL SELECT KeyColumn FROM FKeyTable3) TestKey
GROUP BY KeyColumn
HAVING COUNT(KeyColumn) > 1

In essence, I need to create a temporary table to get KeyColumn count in all foreign key tables, using GROUP BY and HAVING to help counting and filtering.

Note

This original issue was even more complicated. I have to create a KeyColumn based on another subquery. To clarify the issue and to simplify the questioning, I rewrite this issue just to bare essential.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.

Blog at WordPress.com.