根据相同的ID将查询结果拆分为自己的表

时间:2013-10-29 14:31:04

标签: php sql

我目前正在使用以下内容显示一个完整的结果表:

$result = mysqli_query($con,"SELECT * FROM b_tasks_po");

while($row = mysqli_fetch_array($result))

{
echo "<tr>";
echo "<td class='tdclass' width='100'>" . $row['TASK_ID'] . "</td>";
echo "<td class='tdclass' width='100'>" . $row['QTY'] . "</td>";
echo "<td class='tdclass' width='100'>" . $row['CODE'] . "</td>";
echo "<td class='tdclass' width='500'>" . $row['PRODUCT_DESCRIPTION'] . "</td>";
echo "</tr>";
}                   
?>

</table>

这将带来以下内容:

| Task ID  |  Qty  |  Code  |  Description
| 1        |  200  |  AB1   |  Frame 1
| 1        |  350  |  AB2   |  Frame 2
| 2        |  100  |  AB3   |  Frame 3
| 2        |  120  |  AB4   |  Frame 4
| 2        |  300  |  AB5   |  Frame 5

这就是我想要的,我不知道如何做到这一点。我需要为每组ID创建一个新表。例如:

TABLE ONE

| Task ID  |  Qty  |  Code  |  Description
| 1        |  200  |  AB1   |  Frame 1
| 1        |  350  |  AB2   |  Frame 2

TABLE TWO

| Task ID  |  Qty  |  Code  |  Description
| 2        |  100  |  AB3   |  Frame 3
| 2        |  120  |  AB4   |  Frame 4
| 2        |  300  |  AB5   |  Frame 5

我考虑过按task_id对结果进行分组,但没有任何快乐,我也考虑过使用if语句,但是在我的生活中不能想出如何去做。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您需要对结果进行排序,并在task_id更改时重新打印标题。示例:

<?
$result = mysqli_query($con,"SELECT * FROM b_tasks_po ORDER BY TASK_ID");

$current_task_id = -1;
while($row = mysqli_fetch_array($result))
{
    if($current_task_id != $row['TASK_ID'])
    {
        echo "</table><table>";
        echo "<tr>";
        echo "<th width='100'>Task ID</th>";
        echo "<th width='100'>Qty</th>";
        echo "<th width='100'>Code</th>";
        echo "<th width='500'>Description</th>";
        echo "</tr>";
        $current_task_id = $row['TASK_ID'];
    }
    echo "<tr>";
    echo "<td class='tdclass' width='100'>" . $row['TASK_ID'] . "</td>";
    echo "<td class='tdclass' width='100'>" . $row['QTY'] . "</td>";
    echo "<td class='tdclass' width='100'>" . $row['CODE'] . "</td>";
    echo "<td class='tdclass' width='500'>" . $row['PRODUCT_DESCRIPTION'] . "</td>";
    echo "</tr>";
}

?>

</table>

答案 1 :(得分:0)

我认为你不需要两张桌子。我认为你需要两个结果集。您正在寻找的是where条款:

SELECT *
FROM b_tasks_po
WHERE id = 1;

如果确实想要创建两个表(一般来说这似乎是一个坏主意),那么请查看MySQL中的create table as功能。