使用此架构:
CREATE TABLE LookUp
([docID] varchar(10), [docType] varchar(100), [PartNumber] varchar(100), [internalID] varchar(100));
INSERT INTO LookUp
([docID],[docType],[PartNumber], [internalID])
VALUES
('D0305415', 'docTypeSub', 'X0455', null),
('D0157632', 'docTypeMain', null, 'XY05570-XY05571'),
('D0181511', 'docTypeMain',null, 'XY05572-XY05573'),
('D0157633', 'docTypeMain',null, 'XY06380-XY06381'),
('D0156037', 'docTypeSub', 'X0326', null),
('D0151874', 'docTypeMain', null, 'XY05345');
CREATE TABLE Links
([docIDTop] varchar(10), [docIDBottom] varchar(10));
INSERT INTO Links
([docIDTop],[docIDBottom])
VALUES
('D0157632', 'D0305415'),
('D0181511', 'D0305415'),
('D0157633', 'D0305415'),
('D0151874', 'D0156037');
有没有办法优化这个查询而不使用嵌套的'select',我认为有一种方法,但我记不清了; P。 Lookup表中有一对多关系,当doctype为'doctypeSub'时,有一个主行,在链表中用于与查询表(再次)及其详细信息的关系。
SELECT * FROM
(SELECT INTERNALID,
(SELECT PARTNUMBER
FROM LOOKUP X2
WHERE X2.DOCID = Z.DOCIDBOTTOM) PARTNUMBER
FROM LOOKUP X
INNER JOIN LINKS Z
ON X.DOCID = Z.DOCIDTOP) TB
答案 0 :(得分:1)
我发现很难弄清楚你的查询应该做什么。但是,我认为这是等价的:
SELECT X.INTERNALID, X2.PARTNUMBER
FROM LOOKUP X INNER JOIN
LINKS Z
ON X.DOCID = Z.DOCIDTOP INNER JOIN
LOOKUP X2
ON X2.DOCID = Z.DOCIDBOTTOM;