2016-01-13 98 views
0

我已經看過兩個表合併爲一個語句,SQL,但是我的例子網上找結合3個或更多的外觀複雜,我掌握......結合三個SQL語句到一個

我要找把3個陳述合併成一個,我相信它應該是可能的。 下面是我試圖實現的一些僞代碼。

Select tagId from tags where tagName = "test" 
-> 
Select photoId from photoTags where tagId = (tagId from previous statement) 
-> 
Select * from pictures where id = (photoId from previous statement) 

我怎樣才能把它合併成一個聲明?我對使用JOIN有一個簡單的理解,但我不明白多個連接。

我試圖做什麼甚至可能作爲一個聲明?

感謝

+0

你是對的,我編輯了我的問題。我的意思是巢巢加入。 – JoshUnknown

回答

2

您應該可以使用這樣的查詢訪問圖片:

SELECT p.* 
FROM pictures p 
    INNER JOIN photoTags pt on pt.photoId = p.id -- Join tables pictures and photoTags 
    INNER JOIN tags t on pt.tagId = t.tagId -- join tables photoTags and tags 
WHERE t.tagName = "test" 

它選擇從pictures表中的所有列,並通過tagName="test"

+0

非常好,那正是我在找的東西。我只是將where子句添加到語句的結尾以便通過tagName進行搜索。 謝謝,我仍然不明白「p」在哪裏。或「點」。來自雖然。 – JoshUnknown

+0

@JoshUnknown是的,我忘了添加'WHERE'子句,我已經更新了答案 – dotnetom

+0

現在糾正它是有意義的,它是表名的簡寫。 再次感謝! – JoshUnknown

0
SELECT T.TagId,PT.PhotoId,P.* FROM Tag T 
JOIN photoTags PT On PT.tagId =T.TagId 
JOIN pictures P On P.Id=PT.PhotoId 
WHERE T.TagName="test" 
0

過濾數據試試這個

SELECT p.* 
FROM pictures p 
    JOIN photoTags pt on pt.photoId = p.id 
    JOIN tags t on pt.tagId = t.tagId 
WHERE t.tagName = "test"