I'm using SQL Server 2008 and I have 3 tables, x
, y
and z
. y
exists to create a many-to-many relationship between x
and z
.
x y z
-- -- --
id xid id
zid sort
All of the above fields are int
.
I want to find the best-performing method (excluding denormalising) of finding the z
with the highest sort
for any x
, and return all fields from all three tables.
Sample data:
x: id
--
1
2
y: xid zid
--- ---
1 1
1 2
1 3
2 2
z: id sort
-- ----
1 5
2 10
3 25
Result set should be
xid zid
--- ---
1 3
2 2
Note that if more than one z
exists with the same highest sort
value, then I still only want one row per x
.
Note also that in my real-world situation, there are other fields in all three tables which I will need in my result set.