i have two tables and i want to select top row from child table? there are relation by two tables by id. what can i do please help me????
+1
A:
SELECT TOP ...
with an appropriate where clause and/or join should do what you're looking for; there are lots of questions and answers about its use here on SO.
Example:
CREATE TABLE a (pid int, tstamp datetime)
go
CREATE TABLE b (fid int, foo varchar(254))
go
INSERT INTO a (pid, tstamp) VALUES (1, '2010-01-12')
INSERT INTO a (pid, tstamp) VALUES (2, '2010-01-02')
INSERT INTO a (pid, tstamp) VALUES (3, '2010-01-01')
INSERT INTO a (pid, tstamp) VALUES (4, '2010-01-24')
INSERT INTO b (fid, foo) VALUES (1, 'one')
INSERT INTO b (fid, foo) VALUES (2, 'two')
INSERT INTO b (fid, foo) VALUES (3, 'three')
go
SELECT TOP 2 b.foo
FROM a
INNER JOIN b ON a.pid = b.fid
ORDER BY a.tstamp
Returns two rows:
'three'
'two'
T.J. Crowder
2010-01-19 11:07:44
A:
Not enough details and seeing more of what you've tried would help with building a better answer, but if a is the parent table and b the child...
SELECT TOP 1 b.*
FROM b
JOIN a ON (a.ID = b.ID)
WHERE a.ID = someParentID
AND b.SomeField = "someChildCriteria"
ORDER BY b.ID DESC -- or by whatever field needs to be topmost
Darth Continent
2010-01-21 14:42:59