2017-04-16 120 views
0

我有兩個表的第一個表GroceryStores看起來像這樣如何避免對我的查詢使用子查詢?

GsName | OrganizationId 
----------------------- 
'Olymp'| 1 
'Carul'| 2 
'Caref'| 3 
'Viveo'| 2 
'Suces'| 4 

第二個表組織看起來像這樣

Id | Code | ParentOrganizationId 
-------------------------------- 
1 | 'AB' | 0 
2 | 'CD' | 3 
3 | 'EF' | 4 
4 | 'GH' | 0 

凡GroceryStores.OrganizationId和Organizations.Id是相同的。

該查詢應該返回與給定的OrganizationId及其相應的ParentOrganization匹配的所有GsName。

我已經試過此查詢但當GroceryStore只屬於一個組織,而是一個GroceryStore可以有ParentOrganization和GrandparentOrganization和不同GroceryStores可以屬於同一個組織它纔會起作用。此外,一個GroceryStore可以屬於一個組織和該組織可能沒有ParentOrganization

SELECT GsName 
FROM GroceryStores INNER JOIN Organizations 
ON ParentOrganizationId = Id 
WHERE OrganizationId = @Organization 
OR WHERE OrganizationId = (SELECT ParentOrganizationId FROM Organizations 
WHERE Id = @Organization) 
+0

>當子查詢返回多個GsName時,我的查詢失敗。 根據給定的數據,它不應該失敗,因爲只會有一個parentorganizationId。你能展示你正在尋找的例外輸出嗎?我的猜測是你想遍歷層次結構並顯示所有雜貨店 – ughai

+0

當我將子查詢作爲ParentOrganizationId = @Organization時,出現錯誤「子查詢返回多個值」的錯誤,但我在此問題中修復了此錯誤。但我仍然沒有得到我期待的結果。因此,如果我聲明變量組織並將其值設爲2,則查詢應返回'Carul','Viveo','Caref'和'Suces' – AleAng

+0

是否使用SQL Server? – ughai

回答

0

你爲什麼不嘗試,在地方平等的,當你說平等,你必須確保SUBQUERY只返回1行,如果你在查詢

SELECT GsName 
    FROM GroceryStores INNER JOIN Organizations 
    ON ParentOrganizationId = Id 
    WHERE OrganizationId = @Organization 
    OR WHERE OrganizationId IN (SELECT ParentOrganizationId FROM Organizations 
    WHERE Id = @Organization) 
0

使用LIMIT 1想既然你需要遍歷父層次,使用recursive CTE這樣你可以這樣做:

WITH Org 
AS 
(
    SELECT Id,ParentOrganizationId 
    FROM Organizations 
    WHERE Id = @Org 
    UNION ALL 
    SELECT O.Id,O.ParentOrganizationId 
    FROM Org O1 
    INNER JOIN Oranizations O 
    ON O1.ParentOrganizationId = O.Id 
) 
SELECT GsName 
FROM GroceryStores 
WHERE OrganizationId IN 
(
    SELECT Id FROM Org 
) 
0

爲防止您的查詢在執行過程中失敗,請將您的查詢更改爲此, 請注意,我已將=替換爲IN

SELECT GsName 
FROM GroceryStores INNER JOIN Organizations 
ON ParentOrganizationId = Id 
WHERE OrganizationId = @Organization 
OR WHERE OrganizationId IN (SELECT ParentOrganizationId FROM Organizations 
WHERE Id = @Organization)