2014-04-01 191 views
0

DBMS是我正在使用Mysql。我有這些表:SQL查詢:加入

路徑表:

id idSentence idPath token  isTV idC 
1 s0001  p1  test1  true ic000041 
2 s0001  p1  test2  true ic000041 
3 s0002  p2  test3  true ic000042 
4 s0002  p3  test4  false ic000042 
5 s0002  p3  test5  true ic000042 
6 s0002  p4  test6  false ic000042 
7 s0002  p4  test7  true ic000042 
8 s0002  p4  test8  true ic000042 
9 s0002  p4  test9  false ic000042 
10 s0003  p5  test10  false ic000044 
11 s0003  p5  test11  false ic000044 
12 s0003  p5  test12  false ic000044 
13 s0003  p6  test13  false ic000044 
14 s0003  p6  test14  true ic000044 

關係表:

id id2 rel 
    3 4  nsubj 
    4 5  dobj 
    6 7  pobj 
    8 9  nsubjpass 
    10 11 pobj 

內容表:

idC  tag 
    ic000040 a 
    ic000041 p 
    ic000042 div 
    ic000043 b  
    ic000044 i 

我想創建一個查詢,對於每個idSentence(路徑表)我選擇每個帶有idSentence,idPath,令牌,isTV,rel和tag的元組,並使用以下條件:

  • 我想選擇僅包含在ISTV
  • 的至少一個值「真」我想選擇僅用於實施例2和3之間(長度不同idPath的用於路徑表我得到的idPath以下長度:1,3和2與以下查詢:select count(distinct(idPath))as cc from path group by idSentence;所以在這種情況下,我只想得到3和2);
  • 我想選擇2到3之間的每個idPath的長度(例如,查詢:select count(*)as cc from path group by idPath,得到:2,1,2,4,3, 2,我會選擇只值:2,2,3,2)

我創造了這個查詢:

SELECT p.idSentence, p.idPath, p.token, p.isTV, r.rel, t.tag 
    FROM path p LEFT OUTER JOIN relation r 
     ON (p.id = r.id) JOIN content t ON(p.idC=t.idC) 
    JOIN 
     (select idPath, max(case when p.isTV = 'true' then 1 else 0 end) as HasTv, 
     (case when COUNT(*) between 2 and 3 then 1 else 0 end) as Has 
     from path p 
     group by idPath 
    ) pf 
    on p.idPath = pf.idPath and 
    pf.HasTv = 1 and pf.Has = 1; 

,但我要補充也是至關重要的連接條件:

 select count(distinct(idPath)) as cc from path group by idSentence 

如何修改查詢以添加此條件?通過下面的語句

select count(*) as cc from path group by idPath 

我已經添加了條件

(case when COUNT(*) between 2 and 3 then 1 else 0 end) as Has 

我所測試的查詢,並在部分工作原理:QUERY

回答

0

要檢查的數量每個序列中不同的路徑必須按idSequence分組,所以不能只爲另一列分組的子查詢設置另一個連接條件。

您最好的選擇是加入不同的連接條件的另一個子查詢(我簡化您的查詢的一部分有點提高可讀性):

SELECT p.idSentence, p.idPath, p.token, p.isTV, r.rel, t.tag 
FROM path p 
LEFT JOIN relation r ON p.id = r.id 
JOIN content t ON p.idC = t.idC 
JOIN 
(SELECT idPath, 
      MAX(isTV = 'true') AS HasTv, 
      COUNT(*) AS pathLength 
    FROM path 
    GROUP BY idPath 
) pf 
ON p.idPath = pf.idPath 
    AND pf.HasTv = 1 
    AND pathLength BETWEEN 2 AND 3 
JOIN 
(SELECT idSentence, COUNT(DISTINCT(idPath)) AS paths 
    FROM path 
    GROUP BY idSentence 
) ps 
ON p.idSentence = ps.idSentence 
    AND ps.paths BETWEEN 2 AND 3 

檢查Sqlfiddle