2010-01-19 77 views
-1

我有兩個表,我想從子表中選擇頂行? 有id由兩個表的關係。 我能做些什麼請幫助我?如何從子表中選擇頂行

+5

您可以先向我們展示您的嘗試...... – 2010-01-19 11:05:23

回答

1

SELECT TOP ...用適當的where子句和/或join應該做你想要的;關於它在SO上的使用,有lots of questions and answers

例子:

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 

返回兩行:

'three' 
'two' 
0

沒有足夠的細節和看到更多的,你已經嘗試將與建立一個更好的答案幫助什麼,但如果一個是父表和b孩子...

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