2013-05-12 36 views
0

我試圖解釋我現在面臨的一個問題。 實際上,我設計了一個表格,以便跟蹤由用戶在一個NLP引擎庫中應用的更改。選擇表中的多行(不相同的條件)

我有兩張名爲Token And Lexeme的表。每個標記都有一個直接連接到一個lexeme表的行。並且通過查找令牌表,我總能找到最新的和更新的詞位。

這裏是他們的方案:

Token Table: 
+-----+----------+----------+ 
| Id | token |LexemeId* | 
+-----+----------+----------+ 
LexemeId refers to a row inside of lexeme table. 

詞位表:

+-----+---------------------+-------------+ 
| Id | some information |UpdatedFrom* | 
+-----+---------------------+-------------+ 
* UpdatedFrom field refers another row inside of Lexeme Table. 

空意味着沒有與此相關的令牌(語義)更多的行。

一個例子:

Token Table: 
+-----+----------+----------+ 
| 0 | A  |4   | 
| 1 | B  |1   | 
+-----+----------+----------+ 


Lexeme Table: 

+-----+----------------------+-------------+ 
| 0 | A information#1  |NULL   | 
| 1 | B information  |NULL   | 
| 2 | A information#2  |0   | 
| 3 | A information#3  |2   | 
| 4 | A information#4  |3   |  
+-----+----------------------+-------------+ 

我希望我可以清除空氣中。 我想編寫一個存儲過程來收集與每個令牌相關的所有記錄。例如令牌「A」,我希望有一個數組(或數據表)看起來是這樣的:

+-----+----------------------+-------------+ 
| id | informations   | updated from| 
+-----+----------------------+-------------+ 
| 0 | A information#1  |NULL   | 
| 2 | A information#2  |0   | 
| 3 | A information#3  |2   | 
| 4 | A information#4  |3   |  
+-----+----------------------+-------------+ 

任何人有任何想法,以幫助我....在

我的知識sql成績單彙總爲更新,插入和選擇語句,而不是更多!

在先進的感謝...

+1

哪個RDBMS(MySQL,Oracle,SQLServer,PostgreSQL等)是這樣的?您可以在大多數RDBMS的單個查詢中(通過遞歸公用表表達式)執行此操作,但MySQL將是例外情況。 – 2013-05-12 14:00:04

回答

2

假設這是在支持遞歸的CTE的RDBMS,請嘗試:

with cte as 
(select t.id TokenId, t.token, l.Id, l.SomeInformation, l.UpdatedFrom 
from Token t 
join Lexeme l on t.LexemeId = l.id 
union all 
select t.TokenId, t.token, l.Id, l.SomeInformation, l.UpdatedFrom 
from cte t 
join Lexeme l on t.UpdatedFrom = l.id) 
select Id, SomeInformation, UpdatedFrom 
from cte 
where TokenId=0 /* token = 'A' */ 

SQLFiddle here

+0

哇。我不知道遞歸'with'是可能的。我在'oracle'下嘗試了這是我的世界,它仍然工作,但它要求列列表。第一行然後讀取'cte(token,id,someinformation,updatedfrom)as'。 http://sqlfiddle.com/#!4/d226e/3 – hol 2013-05-12 14:41:15

+0

@hol:是的,在支持它們的RDBMS之間,遞歸CTE語法存在細微差別 - 例如,在PostgreSQL中,您需要包含'recursive'關鍵字。我記得,Oracle在v11之前並不支持遞歸CTE(Oracle 10有非遞歸CTE),但你總是可以用'connect by'做類似的事情。 – 2013-05-12 15:54:46

+0

是的,我熟悉'connect by',但這在我看來更容易(至少在某些情況下)。 – hol 2013-05-12 19:22:28