加入PHP和MySQL只返回指定值?

时间:2014-04-11 04:07:31

标签: php mysql database join

我似乎无法理解JOINS这个概念听起来很美。在这一点上,我不确定以下哪个是我的问题,但我真的很想帮助解决这个问题。我在这里看了好几篇文章,甚至还参加了W3Schools测试以及阅读材料,但我无法找到解决方案。一本书?当然,哪一个?我并不反对学习,只是不知道从哪里开始。

问题是我有三个表,其中包含我需要的全部信息,但我只能匹配一行(即如果profile.person = user.id)。这使我能够LEFT JOIN个人姓名,其中profile.person数值是匹配的,这样当表格显示时,它不会显示数字。这是有道理的,但是当我走得更远时,我觉得爱丽丝梦游仙境并且很困惑。

我要做的是讲故事,拉出故事的帖子,确定故事的系列,然后是发布故事的用户。

我的表格如下:

Series Table
PID INT, name VARCHAR, episodes INT
(episodes = # of stories in series)

Stories Table
PID INT, name VARCHAR, series INT, posts INT
(both series and posts = # items under them)

Storyparts Table
PID INT, story INT, position INT, port INT, content MEDIUMTEXT
(story is the ID of the story it belongs too, position is the order it should be
 displayed in, port is the ID of the character who is telling the story,
 content is the post itself (text))

Characters Table
PID INT, name VARCHAR, faction INT, imgport VARCHAR, imgmain VARCHAR, age INT,
hometown VARCHAR, bio MEDIUMTEXT
(both imgport and imgmain store the file names of their images "Portrait and Main")

我想要做的是加载一个故事并显示其name,该系列的name,并显示该字符的imgport,然后显示{角色的{1}},然后是name。我将它们存储到变量后显示它们很好,我的问题是我该怎么做?我的桌子有问题吗?我没有收集到足够的信息来使它工作,或者有没有办法从一个表中提取所有信息,而不是存储在另一个表中的单个值?

到目前为止我的代码:(在此之后我有while循环以及if语句来过滤掉不需要的帖子,但我确信这远远超出了良好的做法。)

content

1 个答案:

答案 0 :(得分:1)

$db->query("
   select st.name as story_name, se.name as series_name, 
   c.imgport, c.name, sp.content from series as se 
   left join stories as st on se.pid = st.pid
   left join character as c on se.pid = c.pid
   left join storyparts as sp on se.pid = sp.pid");

我相信这会做你想要的。如果您需要加入多个表...然后添加更多联接:)