我已经使用了2天,现在转向stackoverflow寻求帮助。我试图为用户的每一篇文章返回display_name以查找“故事”,其中故事(SID)可以有多个用户(也就是多个写作ID,这里称为WID)。
除了每一篇文章的显示名称始终相同外,一切都有效。当我为$ getauthor做一个var_dump()时,我简单地得到wp_users中所有display_names的数组。但我需要的是只返回在写作和故事表中写入该故事(SID)的写作表中写一篇文章(WID)的作者的显示名称。
更清晰一点: 当有人启动博客帖子(称为故事)时,会在该故事中为具有新SID的用户ID创建记录。然后,当人们添加到该SID时,每个添加都在写入表中给出具有相同SID的WID记录。我的代码正在做的是返回所有结果(写作文件)的SID的ORIGINAL作者,实际上应该发生的是每个WID应该有添加该部分的作者。
应该看起来像:
Author: Kate
This is my blog
Author: Mike
This is my addition.
但它看起来像是:
Author: Kate
This is my blog
Author: Kate
This is my addition.
这是数据库架构:
wp_users表:
ID
display_name
故事表:
SID
ID
story_name
写作表:
WID
ID
SID
approved
text
代码:
<?php
global $wpdb;
$user_ID = get_current_user_id();
// get the SID
$the_SID = ( isset( $_GET['writing'] ) ) ? $_GET['writing'] : false;
$results = $wpdb->get_results("
SELECT wp_users.ID, wp_users.display_name,
stories.ID, stories.SID, stories.story_name, stories.category,
writing.ID, writing.text, writing.approved
FROM stories
JOIN wp_users ON stories.ID = wp_users.ID
JOIN writing ON stories.SID = writing.SID
WHERE (stories.SID = $the_SID) AND (writing.approved = 'Y')");
$sql = "SELECT display_name FROM wp_users where ID = ". $results->writing.ID .";";
$getauthor = $wpdb->get_results($sql);
$author = $getauthor[0]->display_name;
?>
<?php
foreach ($results as $result) {
echo "<br>" . "Author: " . $author . "<br>" . $results[0]->text . "<br>";
}
?>
答案 0 :(得分:1)
这是您的查询:
SELECT wp_users.ID, wp_users.display_name,
----------------^
stories.ID, stories.SID, stories.story_name, stories.category,
---------------^
writing.ID, writing.text, writing.approved
---------------^
FROM stories JOIN
wp_users
ON stories.ID = wp_users.ID JOIN
writing
ON stories.SID = writing.SID
WHERE (stories.SID = $the_SID) AND (writing.approved = 'Y');
标识的列都具有相同的名称ID
。您应该为它们定义单独的别名:
SELECT wp_users.ID as userID, wp_users.display_name,
stories.ID as storiesID, stories.SID, stories.story_name, stories.category,
writing.ID as writingID, writing.text, writing.approved
FROM stories JOIN
wp_users
ON stories.ID = wp_users.ID JOIN
writing
ON stories.SID = writing.SID
WHERE (stories.SID = $the_SID) AND (writing.approved = 'Y');
那么也许这会奏效:
$sql = "SELECT display_name FROM wp_users where ID = ". $results->writingID .";";
但是,只需再次加入wp_users
,即可在同一查询中获得所需内容:
SELECT u.ID as userID, u.display_name,
s.ID as storiesID, s.SID, s.story_name, s.category,
w.ID as writingID, w.text, w.approved,
uw.display_name as writer_name
FROM stories s JOIN
wp_users u
ON s.ID = u.ID JOIN
writing w
ON s.SID = w.SID JOIN
wp_users uw
ON w.ID = uw.ID
WHERE (s.SID = $the_SID) AND (w.approved = 'Y');