2011-02-12 62 views
0

嘿,那里,我需要一些MYSQL连接的帮助,我真的不知道如何实现,或者如果MySQL允许的话。MySQL多表连接ID

我有一些表设置,post_controller,post_text,post_photo,post_link。

post_controller具有所有ID,post_text,post_photo,post_link表不能有条目,除非post_controller有一个id条目(外键)。我这样做是因为我有不同类型的帖子,我想要检索它们,而不管帖子的类型如何,所以我只是在主表中使用ID。

我想知道的是,我如何加入3表与主表,形成所有职位的大阵,可以说我想职位1至20 ..是否有可能我加入每个类似于每个表的帖子类型。

 
post_contoller 

id userid type time 
1  2  1  00:00 
2  4  1  00:00 
3  5  2  00:00 
4  23  2  00:00 
5  8  3  00:00 
 
 
post_text 

id content  title 
1 {sometext} {sometext} 
2 {sometext} {sometext} 
 
 
post_photo 

id content  hash 
3 {sometext} {somehash} 
4 {sometext} {somehash} 
 
 
post_link 

id content  desc  link 
5 {sometext} {sometext} {somelink} 
 

结束所得的数据集。

 
post_photo 

id userid type time content  title  desc  link  hash 
1  2  1  00:00 {sometext} {sometext} 
2  4  1  00:00 {sometext} {sometext} 
3  5  2  00:00 {sometext} 
4  23  2  00:00 {sometext}         {somehash} 
5  8  3  00:00      {sometext}{somelink} 
 

通过在post_controller中加入3个关于主ID的表,可以实现此结果集。如果是,请解释,如果没有,请尽可能提出替代解决方案。

谢谢。

+0

您检查了`UNION`或'左JOIN`?其中任何一个应该以某种形式得到你想要的东西。 – jswolf19 2011-02-12 02:55:20

回答

1

是的,这是可能的:

SELECT c.*, 
      IFNULL(IFNULL(p.content, t.content), l.content) AS content, 
      t.title, 
      l.desc, 
      l.link, 
      p.hash 
    FROM post_contoller c 
LEFT JOIN post_text t ON t.id = c.id 
LEFT JOIN post_photo p ON p.id = c.id 
LEFT JOIN post_link l ON l.id = c.id 
+0

看起来很有希望,我会尝试一下,看看它是否适合我。 – 2011-02-12 03:02:13