我有两个表,我想从子表中选择顶行? id有两个表的关系。 我该怎么办请帮助我????
答案 0 :(得分:1)
SELECT TOP ...
应该做你正在寻找的事情;关于它在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'
答案 1 :(得分:0)
没有足够的详细信息并且看到更多您尝试过的内容有助于建立更好的答案,但如果 a 是父表, 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