如何将一对多关系的数据从MySQL处理到PHP

如何将一对多关系的数据从MySQL处理到PHP,php,mysql,one-to-many,Php,Mysql,One To Many,我使用下面的查询返回关于一个习惯的数据 一个习惯可以有很多步骤和很多评论 当我运行下面的查询时,它会在每个步骤和注释中重复该习惯的数据 SELECT habit_id, habit_user_id, habit_name, habit_category_id, habit_description, habit_target_user, habit_up_votes, habit_down_votes, step_id, step_descrip

我使用下面的查询返回关于一个习惯的数据

一个习惯可以有很多步骤和很多评论

当我运行下面的查询时,它会在每个步骤和注释中重复该习惯的数据

        SELECT 
        habit_id, habit_user_id, habit_name, habit_category_id, habit_description, habit_target_user, habit_up_votes, habit_down_votes, 
        step_id, step_description, 
        comment_id, comment_user_id, comment_description
        FROM habits, steps, comments 
        WHERE habit_id = ? 
        AND habit_id = step_habit_id
        AND habit_id = comment_habit_id
        ORDER BY step_order
示例输出(ID应足以了解发生了什么):

我希望能够获取返回的数据并将其保存在一个数组中

array("habit_id" => 1, "step_id" => array(1, 2), "comment_id" => array(1, 2, 3));
我能想到的唯一方法是:

执行3个独立的查询1获取习惯数据,1获取该习惯的步骤,1获取该习惯的注释

通过按原样使用上述查询,并使用习惯数据构造一个新数组,然后在所有行中循环,并为步骤和注释构造一个新数组,同时确保没有添加重复项

这听起来太低效了,有人能建议一个更好的方法吗?要么修改我的查询,为PHP提供更可行的数据,要么在PHP中使用一些技巧。我曾一度考虑将数据连接到查询中的步骤和注释的数组中,但我认为这应该是PHP的工作,以这样的方式操作数据。
我希望以这种方式获取数据的原因是返回数据以在Angularjs应用程序中使用。

我会这样做。如果这能解决你的问题,请告诉我

<?php

$test = NULL;
$test['habit_id']= $habitID; // I assume $habit is known;
$query = "SELECT * FROM steps
        WHERE habit_id = '".$habitID."';";
$result= mysql_query($query, $con);
while($row=mysql_fetch_array($result))
    $test['step_id'][]=$row['step_id'];

$query= "SELECT * FROM comments 
        WHERE habit_id = '".$habitID."';";
$result= mysql_query($query, $con);
while($row=mysql_fetch_array($result))
    $test['comment_id'][]=$row['comment_id'];

var_dump($test);

?>

查询按原样进行。它将返回足够的数据供您迭代并构建所需的数组

$data = array();

// could be any type of loop here. whatever returns data from your query
while($row=mysql_fetch_array($result)) {
    $data['habit_id'] = $row['habit_id'];

    // the in_array check ensures there are no dupes
    if (!in_array($row['step_id'], $data['step_id'])) {
        $data['step_id'][] = $row['step_id'];
    }
    if (!in_array($row['comment_id'], $data['comment_id'])) {
        $data['comment_id'][] = $row['comment_id'];
    }
}

这将比三个单独的查询更有效。确保数据库已正确编制索引。并通过使用EXPLAIN运行查询来检查您是否正在使用这些索引。

至少在示例数据中看起来没有重复。你试过吗?哪个mysql数据库?我已经更新了我的示例数据,你现在明白我的意思了吗?如果步骤数和注释数不相等,distinct是否仍会返回重复的值?如何找到我正在使用的mysql数据库?您的connect语句。根据你的回答,我敢打赌,试着输入distinct,我们可以从那里开始。我将看看你是如何措辞的问题我认为
distinct
会为你清理这个问题虽然这肯定会起作用,我也想过这样做,但我正在寻找一个只需要执行1个查询而不是3个查询的解决方案。我应该在我的问题中明确说明这一点。不过,我越来越有可能不得不采用这种方法
$data = array();

// could be any type of loop here. whatever returns data from your query
while($row=mysql_fetch_array($result)) {
    $data['habit_id'] = $row['habit_id'];

    // the in_array check ensures there are no dupes
    if (!in_array($row['step_id'], $data['step_id'])) {
        $data['step_id'][] = $row['step_id'];
    }
    if (!in_array($row['comment_id'], $data['comment_id'])) {
        $data['comment_id'][] = $row['comment_id'];
    }
}