重要...在我的 RL 项目中,ID 不是 INT,而是 GUID,所以我的数据不是分层的!
我有一张公司表和一张公司之间链接的表。
我需要能够从特定公司 ID 中检索公司列表。
这是我的测试代码...
CREATE TABLE ##corporations
(
CorporationID INT NOT NULL,
CorporationName NVARCHAR(20) NOT NULL
);
CREATE TABLE ##corporationLinks
(
FromCorporationID INT NOT NULL,
ToCorporationID INT NOT NULL
);
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (1, 'Nike')
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (2, 'Cocal Cola')
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (3, 'Apple')
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (4, 'Google')
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (5, 'Amazon')
INSERT INTO ##corporations (CorporationID, CorporationName) VALUES (6, 'Samsung')
INSERT INTO ##corporationLinks (FromCorporationID, ToCorporationID) VALUES (1, 2)
INSERT INTO ##corporationLinks (FromCorporationID, ToCorporationID) VALUES (2, 3)
INSERT INTO ##corporationLinks (FromCorporationID, ToCorporationID) VALUES (4, 5)
INSERT INTO ##corporationLinks (FromCorporationID, ToCorporationID) VALUES (4, 6)
SELECT * FROM ##corporationLinks WHERE FromCorporationID = 2 OR ToCorporationID = 2
/**
Organisations (##corporationLinks) are...
Nike + Coca Cola + Apple + Marcy
and...
Google + Amazon + Samsung
**/
-- How do I eg get a list of companies where Coca Cola is in ... that is where FromCorporationID = 2 OR ToCorporationID = 2 ... result should be Nike, Coca Cola and Apple?
-- How do I eg get a list of companies where Samsung is in ... that is where FromCorporationID = 6 OR ToCorporationID = 6 ... result should be Google, Amazon Cola and Samsung?
DROP TABLE ##corporationLinks
DROP TABLE ##corporations
UDPATE:
如果我需要找到可口可乐所在的公司,那么我会去寻找……
SELECT * FROM ##corporationLinks WHERE FromCorporationID = 2 或 ToCorporationID = 2
然后我会得到2个结果......
FromCorporationID ToCorporationID
-----------------------------------
1 2
2 3
在此之后,我需要查看结果属于哪些公司...
SELECT * FROM ##corporationLinks WHERE FromCorporationID = 1 OR ToCorporationID = 1
SELECT * FROM ##corporationLinks WHERE FromCorporationID = 3 OR ToCorporationID = 3
然后我会再得到一个公司(7):
FromCorporationID ToCorporationID
-----------------------------------
3 7
然后我需要深入了解与 7 相关的公司......
SELECT * FROM ##corporationLinks WHERE FromCorporationID = 7 OR ToCorporationID = 7
并深入研究该结果(猜想它被称为递归)。等等
更新 2:
我已经更新了上面的示例,添加了一个如果搜索是 Coca Cola 应该返回的公司。
上述查询(可口可乐)的预期结果:
CorporationID:
--------------
2
1
3
7