简体   繁体   English

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

[英]Get data from two mysql tables, where row of one table is connected to many in other

I have two mysql database table, one is for posts and other is for comments. 我有两个mysql数据库表,一个用于发布,另一个用于评论。

Post table 发布表

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

And comments table 和评论表

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

Now, How to get posts with bare minimum mysql query requests, so that output is like, 现在,如何获取带有最少的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
            )
        )
    )
)

How about 怎么样

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

It will be helpful if you can provide code to put results in array 如果您可以提供将结果放入数组的代码,将很有帮助

Let me first recommend a better multidimensional array that will be easier to work with. 首先让我推荐一个更好的多维数组,该数组将更易于使用。

Array Format: 数组格式:

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

The above format will be easier to work with especially for direct access into the array and also for the foreach loop. 上面的格式将更易于使用,尤其是对于直接访问数组以及foreach循环而言。

Now for assigning the data from the MySQL result into the array using mysqli_* functions and a while loop do the following: 现在,要使用mysqli_*函数和while循环将来自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 />";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从2个表中获取数据,其中一个表与另一个表相关 - Get data from 2 tables where one table is dependent of the other 使用Codeigniter将表中的一行与MySQL中其他两个表的多行联接 - Join one row from a table with multiple rows of two other tables in MySQL using Codeigniter MySql根据另外两个表的条​​件在一个表中查找数据 - MySql find data in one table based on conditions of two other tables 如何从两个表(如一个表的所有行)以及相对于其他表的第一个表的主键总和中获取数据 - How to get data from two tables like one table all rows and with respect to first table primary key sum of row from other table 尝试用其他两个表中的数据更新一个mySQL表失败 - Attempt to update one mySQL table with data from two other tables is failing MySQL更新一个表,但使用其他两个表中的数据作为更新的一部分 - MySQL Update one table, but use data from two other tables as part of the update mysql-将一个表与另外两个表联接 - mysql - join one table with two other tables 一次从两个表中检索数据,一个表引用另一个表 - Retrieving data from two tables at once with one table referencing the other MySQL:对于表中的每一行,然后从其他表中获取数据 - MySQL: for each row on table then get data from other table 如何从由第三个表连接的两个mySQL表中选择数据? - How can I select data from two mySQL tables connected by a third table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM