2016-01-13 95 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"