Terry
Terry

Reputation: 253

Query help - self referential parent table

I have three tables:

Type
---------------------
TypeID (primary key)
ParentTypeID (foreign key)
TypeDescription (...)

Action
---------------------
ActionID (primary key)
TypeID (foreign key)
ReferenceID (foreign key)

Reference
---------------------
ReferenceID (primary key)
ReferenceDescription (...)

Type is self referential. Action contains instances of Reference and Type through time. I add to Action as each reference passes different stages of completion. Here's the question:

what would my query look like to display the last entry added to Action WHERE ReferenceID = an input variable? I know it is the last entry because it would be the only instance of Type in the list which has no children Types also in the list.

I am happy to clarify if this is too unclear.

Thanks!

Upvotes: 0

Views: 88

Answers (1)

Scott Herbert
Scott Herbert

Reputation: 334

Assuming ActionID is an int identity(1,1) or the like

SELECT TOP 1
  ActionID,
  TypeID,
  ReferenceID
FROM
  Action
WHERE
  ReferenceID = 1
ORDER BY
  ActionID desc

If the last entry per reference ID is all you're after, then I'm not sure you need to worry about that type ID at all.

Upvotes: 1

Related Questions