2015-06-15 33 views
0

我正努力爲我的select語句找出解決方案。我有兩個表:帶有「檢查表」的MS SQL選擇語句

CREATE TABLE Things 
(
    Id int, 
    type int 
) 

CREATE TABLE Relations 
(
    Id int, 
    IdParent int, 
    IdChild int 
) 

我需要根據具體的事物ID來選擇,什麼:從從擁有的東西有Type = -1

  • 所有記錄的東西

    • 所有記錄Type匹配IdChild哪裏IdParent是給定Id的行匹配類型。
    • 如果給Id一排匹配的Type-1或表的關係不存在(如IdParent)我需要從事情

    我有最後一個場景的問題,我嘗試了所有記錄通過加入關係表來做到這一點,但是我不能提出滿足所有情況的條件,有什麼建議嗎?

    UPDATE

    這是我現在該怎麼辦呢。我需要解決給定id不存在於表關係中的情況 - 那麼我需要選擇所有記錄。

    CREATE TABLE Things (id int, type int) 
    CREATE TABLE Relations (id int, parent int, child int) 
    
    INSERT INTO Things VALUES (1, 1) 
    INSERT INTO Things VALUES (2, -1) 
    INSERT INTO Things VALUES (3, 3) 
    INSERT INTO Things VALUES (4, 3) 
    INSERT INTO Things VALUES (5, 2) 
    INSERT INTO Things VALUES (6, -1) 
    
    INSERT INTO Relations VALUES (1, 1, 2) 
    
    DECLARE @id int = 1 
    
    SELECT * FROM Things 
    JOIN Relations R ON R.parent = @id AND Type = R.child OR Type = -1 
    

    所以我必須要解決例如情況@id = 2 - 我需要檢索的所有行(同爲@id = 5,除非它出現在關係中父列的地方)。

    更新2

    我想出了這樣的事情:

    DECLARE @id int = 2 
    DECLARE @type int 
    
    SELECT @type = type FROM Things WHERE Id = @id 
    
    IF @type > -1 
    BEGIN 
    SELECT T.* FROM Things T 
    JOIN Relations R ON (R.parent = @id AND T.Type = R.child) OR T.Type = -1 
    END 
    ELSE 
    BEGIN 
    SELECT * FROM Things 
    END 
    

    我敢肯定,這是可以做不同的,沒有條件IF,優化。

  • +0

    您能否提供原始數據的數據示例以及您想要接收的內容?我保證你會收到一個工作查詢;) – Ionic

    +0

    '事情'和'關係'之間的關係是什麼? – PaulFrancis

    +0

    這是你以後的事情,爲檢索父母和它的孩子:http://stackoverflow.com/a/25551203/57475 – Tanner

    回答

    0
    from Things 
    left outer join Relations 
        on Relations.IdParent = Things.Type 
    where Things.Type = -1 or Relations.IdParent is null