从两个mysql表中获取数据,其中一个表的行连接到另一个表中的许多表

时间:2013-08-19 12:54:03

标签: php mysql

我有两个mysql数据库表,一个用于帖子,另一个用于评论。

发布表

+----+-------+
| ID | texts |
+----+-------+
| 1  | abc   |
| 2  | xyz   |
+----+-------+

评论表

+----+--------+-------+
| ID | postid | texts |
+----+--------+-------+
| 1  | 1      | abc1  |
| 2  | 1      | abc2  |
| 3  | 1      | abc3  |
| 4  | 2      | xyz1  |
| 5  | 2      | xyz2  |
+----+--------+-------+

现在,如何使用最少的mysql查询请求获取帖子,以便输出类似,

$data = array(
    0 => array(
        ID => 1,
        texts => abc,
        comments => array(
            0 => array(
                ID => 1,
                texts => abc1
            )
            1 => array(
                ID => 2,
                texts => abc2
            )
            2 => array(
                ID => 3,
                texts => abc3
            )
        )
    )
    1 => array(
        ID => 2,
        texts => xyz,
        comments => array(
            0 => array(
                ID => 4,
                texts => xyz1
            )
            1 => array(
                ID => 5,
                texts => xyz2
            )
        )
    )
)

2 个答案:

答案 0 :(得分:2)

怎么样

SELECT  *
FROM    Post p LEFT JOIN
        Comments c  ON  p.ID = c.postID

答案 1 :(得分:1)

  

如果您可以提供将结果放入数组

的代码,将会很有帮助

让我首先推荐一个更易于使用的更好的多维数组。

数组格式:

$data = array(
    post.ID => array(
        "texts" => post.texts,
        "comments" => array(
            comments.ID => comments.texts,
        ),
    ),
);

上述格式更易于使用,特别是对于直接访问数组以及foreach循环。

现在使用mysqli_*函数和MySQL循环将数据从MySQL结果分配到数组中,执行以下操作:

//connect to mysql database
$link = $mysqli_connect("localhost","your_user","your_password","your_database");
//form mysql query
$query = "
    SELECT
        post.ID AS post_id,
        post.texts AS post_texts,
        comments.ID AS comments_id,
        comments.texts AS comments_texts
    FROM
        post
        LEFT JOIN comments ON (comments.postid = post.ID)
    WHERE
        posts.ID < 10
";
//run mysql query and return results
$mysqli_result = mysqli_query($link,$query);
//define empty $data array
$data = array();
//loop through result sets fetching string array with each result row
while($row = mysqli_fetch_array($mysqli_result)){
    //set the post text if not already set
    if(!isset($data[$row["post_id"]]["texts"])){
        $data[$row["post_id"]]["texts"] = $row["post_texts"];
    }
    //set the comments data if not NULL otherwise set comments to empty array to maintain structure
    if(!empty($row["comments_id"])){
        $data[$row["post_id"]]["comments"][$row["comments_id"]] = $row["comments_texts"];
    } else {
        $data[$row["post_id"]]["comments"] = array();
    }
}
//free the results set
mysqli_free_result($mysqli_result);
//close connection to mysql database
mysqli_close($link);

//print out the post text with the id of 1 with two line breaks
//be careful using this method unless you are sure that post with id of 1 exists or first check if(isset($data["1"])){...}
print $data["1"]["texts"]."<br /><br />";

//loop through all of the comments for a particular post with id of 1
foreach($data["1"]["comments"] as $key => $value){
    //print out the comment id with a line break
    print "Comment ID: ".$key."<br />";
    //print out the comments texts with two line breaks
    print "Comment: ".$value."<br /><br />";
}

//loop through and print all the post texts and how many comments exist for the post
foreach($data as $key => $value){
    //print the post ID with a line break
    print "Post ID: ".$key."<br />";
    //print the post texts with a line break
    print "Post: ".$value["texts"]."<br />";
    //count the number of comments
    $num_comments = count($value["comments"]);
    //get correct plural form of noun
    ($num_comments==1) ? $comments = "comment" : $comments = "comments";
    //print the number of comments for the post with two line breaks
    print $num_comments." ".$comments." for this post.<br /><br />";
}