在1个查询中获取故事及其所有评论

时间:2017-03-09 09:20:56

标签: php join mysqli

我正在尝试创建一个PHP api,我正在尝试检索新闻故事及其所有注释并将其作为json发送。

这是我到目前为止所拥有的:

$sql = "SELECT * FROM fb_clubnews WHERE clubid='$groupId' AND ori_newsid = 0 ORDER BY newsid DESC LIMIT 10";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $storId = $row["newsid"];

        $commentArray = array();

        $wallAray[] = array("author"=>$row["userid"],
                                "story"=>$row["news"],
                                "date"=>$row["date"],
                                "time"=>$row["time"],
                                "matchid"=>$row["fk_match_id"],
                                "comments"=>$commentsArray);
    }
}

我的问题是,我想避免在sql中创建一个sql并循环遍历它?!第二个内部sql是:

$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";

如何让$ commentArray充满评论。

fb_clubnews的我的数据库结构如下所示:

int newsid (autoincrement),
int userid,
text news,
int data,
int time,
int matchid,
int ori_newsid

希望得到帮助,并提前感谢: - )

1 个答案:

答案 0 :(得分:0)

这样的事情:

$sql = "SELECT *, A.newsid as main_news_id FROM fb_clubnews A LEFT JOIN fb_clubnews B ON B.ori_newsid = A.newsid  WHERE A.clubid='$groupId' AND A.ori_newsid = 0 ORDER BY A.newsid DESC";
$result = $conn->query($sql);
$wallAray = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $storId = $row["main_news_id"];
        if(array_key_exists($storId, $wallAray)) {
            $commentArray[] = $wallAray;
        } else {
            $wallAray[$storId] = array();
            $commentArray = array();
        }

        $wallAray[] = array("author"=>$row["userid"],
                            "story"=>$row["news"],
                            "date"=>$row["date"],
                            "time"=>$row["time"],
                            "matchid"=>$row["fk_match_id"],
                            "comments"=>$commentsArray);
    }
}