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


Split Query Results Into there Own Table Depending on Same ID

我目前使用以下方法显示一个充满结果的表格:

$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 语句,但终其一生都无法弄清楚如何做到这一点。

任何帮助将不胜感激。

您需要

对结果进行排序,并在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>

我认为你不需要两个表。 我认为您需要两个结果集。 您正在寻找的是where子句:

SELECT *
FROM b_tasks_po
WHERE id = 1;

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