2017-06-15 56 views
0

我一直在嘗試幾天來爲所述Entity-Attribute-Value數據庫生成查詢,並且使用sql得到了一點生疏,所以即使經過大量研究我無法設法讓查詢完全按照我的意願進行。對EAV數據庫的查詢會生成太多的「null」s

表的重要組成部分看起來像這樣:

 
ID | concept | modifier 
1 | abc:10 | @ 
2 | abc:22 | @ 
2 | abc:22 | t:f 
2 | abc:78 | @ 
2 | abc:78 | t:x 
3 | kfg:12 | @ 
4 | aqx:23 | @ 
5 | abc:49 | @ 
5 | abc:49 | t:f 
5 | abc:49 | t:g 

我想這樣的一個表:

 
ID | concept | mod_f | mod_other 
1 | abc:10 | null | null 
2 | abc:22 | t:f | null 
2 | abc:78 | null | t:x 
5 | abc:49 | t:f | t:g 

我嘗試讓我已經對這樣的結果:

 
ID | concept | mod_f | mod_other 
1 | abc:10 | null | null 
2 | abc:22 | t:f | null 
2 | abc:22 | null | null 
2 | abc:78 | null | t:x 
2 | abc:78 | null | null 
5 | abc:49 | t:f | null 
5 | abc:49 | t:f | t:g 
5 | abc:49 | null | t:g 
5 | abc:49 | null | null 

這裏是一個生產我的結果代碼:

 
    SELECT t.ID, t.concept, t.modifier, 
     case when t.concept LIKE 'abc:%' and t.modifier = '@' then t.concept end AS "concept", 
     case when t2.modifier = 't:f' then t2.modifier end AS "mod_f", 
     case when t3.modifier LIKE 't:%' then t3.modifier end AS "mod_other" 
    FROM table as t 
    LEFT JOIN table as t2 ON t.ID = t2.ID and t.concept = t2.concept 
    LEFT JOIN table as t3 ON t2.ID = t3.ID and t2.concept = t3.concept 
    WHERE t.concept LIKE 'abc:%' and t.modifier = '@' and 
     (t2.modifier LIKE 't:f' or t2.modifier ='@')and 
     (t3.modifier = 't:g' or t3.modifier = 't:x' or t3.modifier ='@')
ORDER by t.ID asc;

的修復看起來有點簡單,但無論我試圖減少結果的方式比我想要的(東西基本上刪除過多的行少),此時我不知道我需要搜索什麼。

此外,查詢中的「case」部分看起來很髒,我找到了某處並使用它,因爲它起作用(使「@」變爲「null」),所以如果您有任何建議查詢更乾淨,隨時回覆。

+0

你的主鍵是什麼? – Strawberry

+0

它是ID和另一個ID,每行保存相同的編號,所以在本例中沒有提到這個第二個ID。 –

+0

看到PK總是很高興。它通常會提供關於數據結構的更好的概念 - 即使沒有涉及到聯接。 – Strawberry

回答

0

好的,我找到了答案,比我想象的要容易。

GROUP by是答案。我認爲這不會對文字工作,但實際上你可以用最大彙總文本的情況下選擇語句是這樣的:

 
    SELECT t.ID, t.concept, t.modifier, 
     max(case when t.concept LIKE 'abc:%' and t.modifier = '@' then t.concept end) AS "concept", 
     max(case when t2.modifier = 't:f' then t2.modifier end) AS "mod_f", 
     max(case when t3.modifier LIKE 't:%' then t3.modifier end) AS "mod_other" 
    FROM table as t 
    LEFT JOIN table as t2 ON t.ID = t2.ID and t.concept = t2.concept 
    LEFT JOIN table as t3 ON t2.ID = t3.ID and t2.concept = t3.concept 
    WHERE t.concept LIKE 'abc:%' and t.modifier = '@' and 
     (t2.modifier LIKE 't:f' or t2.modifier ='@')and 
     (t3.modifier = 't:g' or t3.modifier = 't:x' or t3.modifier ='@') 
    GROUP by t.ID, t.concept, t.modifier 
    ORDER by t.ID asc; 

這讓我正是我一直在尋找的表格。但這隻適用於因爲mod_other每個概念只能包含1個代碼。