Welcome to dbForumz.com!
FAQFAQ    SearchSearch      ProfileProfile    Private MessagesPrivate Messages   Log inLog in

Query question with 3 FKs

 
   Database Forums (Home) -> Programming RSS
Next:  International Conference WWW/Internet 2010 (2nd c..  
Author Message
kpg

External


Since: Jul 06, 2010
Posts: 4



(Msg. 1) Posted: Tue Jul 06, 2010 9:31 am
Post subject: Query question with 3 FKs
Archived from groups: microsoft>public>sqlserver>programming (more info?)

Novice Query question:

I have a table with 3 foreign keys, for example:

Notes
ID as int
CreatedBy int ;FK User_table.ID
AssignedTo int ;FK User_table.ID
ClosedBy int ;FK User_table.ID
Note nvarchar(max)

and a talbe of users, for example

Users
ID as int
Name as nvarchar(50)
Initials as nvarchar(3)

I need a query that returns the the notes with the initials of the users,
so I tried this:

SELECT n.*, u.Initials AS uCreatedBy, u.Initials AS uAssignedTo, u.Initials
AS uClosedBy FROm Notes as n, Users as u WHERE n.ID = @id AND n.CreatedBy =
u.ID AND n.AssignedTo = u.ID AND n.ClosedBy = u.ID

I get no records, understandable, sinde no record has all three FK's set to
the same user.

What is the proper way to query this?

thanks,
kpg

 >> Stay informed about: Query question with 3 FKs 
Back to top
Login to vote
Scott Morris

External


Since: Aug 28, 2003
Posts: 48



(Msg. 2) Posted: Tue Jul 06, 2010 1:16 pm
Post subject: Re: Query question with 3 FKs [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

"kpg" wrote in message

> Novice Query question:
>
> I have a table with 3 foreign keys, for example:
>
> Notes
> ID as int
> CreatedBy int ;FK User_table.ID
> AssignedTo int ;FK User_table.ID
> ClosedBy int ;FK User_table.ID
> Note nvarchar(max)
>
> and a talbe of users, for example
>
> Users
> ID as int
> Name as nvarchar(50)
> Initials as nvarchar(3)
>
> I need a query that returns the the notes with the initials of the users,
> so I tried this:
>
> SELECT n.*, u.Initials AS uCreatedBy, u.Initials AS uAssignedTo,
> u.Initials
> AS uClosedBy FROm Notes as n, Users as u WHERE n.ID = @id AND n.CreatedBy
> =
> u.ID AND n.AssignedTo = u.ID AND n.ClosedBy = u.ID
>
> I get no records, understandable, sinde no record has all three FK's set
> to
> the same user.
>
> What is the proper way to query this?

You join three times to the Users table - generating one row per type of
user. You might want to outer join to get the assigned-to and closed-by
users (assuming these might be nullable values). Alternatively, you can use
subqueries to generate 1 row per note:

select CreatedBy,
(select Initials from Users where Users.ID = Notes.CreatedBy) as
CreatedInitials,
....
from Notes

More information can be found in BOL - use the index and look for
"subqueries".

 >> Stay informed about: Query question with 3 FKs 
Back to top
Login to vote
--CELKO--

External


Since: Apr 17, 2007
Posts: 417



(Msg. 3) Posted: Tue Jul 06, 2010 5:04 pm
Post subject: Re: Query question with 3 FKs [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Instead of inventign your own programming language, could you use real
DDL instead? Also, please read ISO-11179 rules -- there is no magical
generic ID data element in RDBMS. Is this what you meant?

CREATE TABLE Notes
(note_id INTEGER NOT NULL PRIMARY KEY,
creator_user_id INTEGER NOT NULL
REFERENCES Users(user_id),
assignee_user_id INTEGER NOT NULL
REFERENCES Users(user_id),
closer_user_id INTEGER NOT NULL
REFERENCES Users(user_id),
note_txt VARCHAR (2000));

CREATE TABLE Users
(user_id AS INTEGER NOT NULL PRIMARY KEY,
user_name VARCHAR(50) NOT NULL,
user_initials VARCHAR(3) NOT NULL);

SQL Server will have problems with cycles in the DRI; other products
do not.

>> I need a query that returns the the notes with the initials of the users ..<<

SELECT N.note_id, U.user_initials
FROM Notes AS N, Users AS U
WHERE N.note_id = @in_note_id
AND U.user_id IN
(N.creator_user_id, N.assignee_user_id, N.closer_user_id);

>> no record [sic: rows are not records] has all three FK's set to the same user. <<

How did you enforce that rule?
CHECK (creator_user_id NOT IN (assignee_user_id, closer_user_id)
CHECK (closer_user_id NOT IN (assignee_user_id, creator_user_id)

Can there be NULLs? This does not work so good with them and the
constraints get harder to write.

You might try a different schema design. Pull the user roles out as an
attribute in a relationship table.

CREATE TABLE Notes -- entity
(note_id INTEGER NOT NULL PRIMARY KEY,
note_txt VARCHAR (2000));

CREATE TABLE Users -- entity
(user_id AS INTEGER NOT NULL PRIMARY KEY,
user_name VARCHAR(50) NOT NULL,
user_initials VARCHAR(3) NOT NULL);

CREATE TABLE Note_Assignments
(note_id INTEGER NOT NULL
REFERENCES Notes(note_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
assignment_type CHAR(Cool NOT NULL
CHECK (assignment_type IN ('creator', 'assignee', 'closer')),
PRIMARY KEY (note_id, user_id)
UNIQUE (note_id, user_id, assignment_type);

Look at how the overlapping UNIQUE constraints work to prevent a user
from multiple roles in a note.
 >> Stay informed about: Query question with 3 FKs 
Back to top
Login to vote
Erland Sommarskog2

External


Since: May 30, 2004
Posts: 1649



(Msg. 4) Posted: Tue Jul 06, 2010 5:25 pm
Post subject: Re: Query question with 3 FKs [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

kpg (ipost@thereforeiam) writes:
> Novice Query question:
>
> I have a table with 3 foreign keys, for example:
>
> Notes
> ID as int
> CreatedBy int ;FK User_table.ID
> AssignedTo int ;FK User_table.ID
> ClosedBy int ;FK User_table.ID
> Note nvarchar(max)
>
> and a talbe of users, for example
>
> Users
> ID as int
> Name as nvarchar(50)
> Initials as nvarchar(3)
>
> I need a query that returns the the notes with the initials of the users,
> so I tried this:
>
> SELECT n.*, u.Initials AS uCreatedBy, u.Initials AS uAssignedTo,
> u.Initials
> AS uClosedBy FROm Notes as n, Users as u WHERE n.ID = @id
> AND n.CreatedBy =
> u.ID AND n.AssignedTo = u.ID AND n.ClosedBy = u.ID
>
> I get no records, understandable, sinde no record has all three FK's set
> to the same user.

SELECT n.Note, cre.Name, ass.Name, clo.name
FROM notes n
JOIN users cre ON n.CreatedBy = u.ID
JOIN users ass ON n.AssignedTo = u.ID
JOIN users clo ON n.ClosedBy = u.ID

--
Erland Sommarskog, SQL Server MVP, esquel.RemoveThis@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
 >> Stay informed about: Query question with 3 FKs 
Back to top
Login to vote
kpg

External


Since: Jul 06, 2010
Posts: 4



(Msg. 5) Posted: Thu Jul 08, 2010 10:15 am
Post subject: Re: Query question with 3 FKs [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Erland Sommarskog wrote in


> SELECT n.Note, cre.Name, ass.Name, clo.name
> FROM notes n
> JOIN users cre ON n.CreatedBy = u.ID
> JOIN users ass ON n.AssignedTo = u.ID
> JOIN users clo ON n.ClosedBy = u.ID


Got it. Used LEFT OUTER JOINS to handle nulls. Thanks all.
 >> Stay informed about: Query question with 3 FKs 
Back to top
Login to vote
Display posts from previous:   
Related Topics:
Query question - I have 2 tables. One table (sales) has a salesid and sales amount. The other table (salesrep) has a salesid and name. I want to write a query that will return the max sales amount and the name of the salerep who's responsible for it. The following..

SQL Query Question - I wrote a stored procedure that uses a cursor and a temp table to return values. I would like to change this to a single query if it is possible to improve performance. The source data looks like this. Sorted by ID then DateValue. ID ...

aggregate query question - I have a recurring pattern in my queries that I am solving by using CTEs and temp tables and am just wondering if there is a better way. I continually have to extract min or max values that occurred between 2 dates but in addition to the min or max I...

Date query question - Hello All, I would like to get all the records in a table with the date = 8/15/08. The date field is dpolltime which is a datetime field.Here is my query SELECT TOP (100) PERCENT AVG(dbo.StatisticalNumeric.nValue_Avg) AS avg_value,..

Question on anatomy of a query - I was looking at an article by Plamen Ratchev (which I had printed a while ago but can't find it online anymore) where he states that the first thing a query does if there are 2 tables involved is create a Cartesian Product (cross Join) between each..
   Database Forums (Home) -> Programming All times are: Pacific Time (US & Canada)
Page 1 of 1

 
You can post new topics in this forum
You can reply to topics in this forum
You can edit your posts in this forum
You can delete your posts in this forum
You can vote in polls in this forum



[ Contact us | Terms of Service/Privacy Policy ]