2011-01-20 89 views
3

我試圖加入3個表,以某種方式進行分層內部連接,並從第三個表中獲取數據。我的出發點是文章列表中的article_number(156118)。這裏是工作的SQL語句和表結構,但是必須有一種方法將所有這些連接在一起,對嗎?MySQL加入問題

// Get the parent task from the article 
select task_parent 
from article a, tasks t 
where a.task_id = t.task_id 
and a.article_number = 156118 

// Get the task id for the 'Blog' task 
select task_id 
from tasks 
where task_parent = 26093 
and task_name like '%blog%' 

// Get ALL the blog record 
select * 
from blogs 
where task_id = 26091 

---------Tables------------ 

* article table * 
id | article_number | task_id 
1 | 156118   | 26089 


* tasks table * 
id | task_name | task_parent 
26089 | article | 26093 
26091 | blogs  | 26093 
26093 | Main Task | 26093 


* blog table * 
id | task_id | content 
1 | 102  | blah 
2 | 102  | blah 
3 | 102  | blah 

------------- 

*如何獲取所有博客的數據,只要使用的article_number 1條SQL語句?

在此先感謝!

回答

4

編輯:重讀問題後的修訂答案。您需要兩個連接到任務表。一個獲得文章任務的父母,另一個獲取與文章任務相同的父任務。

select b.id, b.task_id, b.content 
    from article a 
     inner join tasks t1 
      on a.task_id = t1.task_id 
     inner join tasks t2 
      on t1.task_parent = t2.task_parent 
       and t2.task_name like '%blog%' 
     inner join blogs b 
      on t2.task_id = b.task_id 
    where a.article_number = 156118 
+0

完美的喬......這就是我一直在尋找,它正確運行。謝謝!!!! – user583316 2011-01-22 02:05:41

1

看起來像你想,以配合他們在一起,只是使用的文章編號作爲參數... 嘗試:


select b.* 
from blogs b, tasks t, tasks tp, article a 
where b.task_id = t.task_id 
and t.task_parent = tp.task_id 
and tp.task_id = a.task_id 
and a.article_number = 156118 
0

在這裏你去。

SELECT * FROM a 
INNER JOIN tasks USING (a.article_number) 
INNER JOIN blogs USING (a.article_number) 
WHERE a.article_number = 156118;