一對多的關係與此架構:優化一個在同一個表查詢
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');
有沒有辦法不使用優化這個查詢嵌套的「選擇」,我覺得有一種方法,但我不能記住; P。查找表在內部有一對多的關係,當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
你能描述一下你想要查詢嗎? –