仅选择1个不同的列 - SQL

时间:2016-02-21 20:15:54

标签: php html mysql

我的数据库中有这样的表

orderID| productID | qty
1        5           1
1        2           1
1        6           1
1        4           1
2        9           1
2        5           2
2        6           1

我想以与此

类似的方式将其输出到我的HTML / php页面
Order ID:1
Product ID | Qty
5          | 1
2          | 1
6          | 1
4          | 1
Order ID:2
Product ID | Qty
9          | 1
5          | 2
6          | 1

这甚至可以吗?我试图使用DISTINCT,但每个orderID只输出1行。这是我目前使用ORDER BY语句输出的最接近的方式,但这会使数据库中每一行都有标题。

<?php
    if ($query = "SELECT * FROM productOrders ORDER BY orderID"){
        $result = mysqli_query($connection, $query);

        if (mysqli_num_rows($result) > 0)
    {
         while($row = mysqli_fetch_assoc($result)) 
         {
        ?>                                          

    <table>
    <tr>
        <th>Order ID: <?php echo $row['orderID'] ?></th>
    </tr>
    <tr>
        <th>Product ID</th>
        <th>Qty</th>
    </tr>
    <tr>
        <td><?php echo $row['productID'] ?></td>
        <td><?php echo $row['qty'] ?></td>
    </tr>

    </table>
<?php
        }
    } 
 ?>

2 个答案:

答案 0 :(得分:0)

试试这个

            <?php
    $query = "SELECT * FROM productOrders ORDER BY orderID";
                if ($query){
                    $result = mysqli_query($connection, $query);

                    if (mysqli_num_rows($result) > 0)
                {
                     while($row = mysqli_fetch_assoc($result)) 
                     {
                          $id=$row['orderID'];
                          $sql="SELECT orderID, qty FROM productOrders WHERE orderID=$id";
                          $q=mysqli_query($connection,$sql);
                          if(!$q){ echo "error"; }
                           else { while($row1=mysqli_fetch_assoc($q)){

            ?>

                <table>
                <tr>
                    <th>Order ID <?php echo $id; ?></th>
                </tr>
                <tr>
                    <th>Product ID</th>
                    <th>Qty</th>
                </tr>
                <tr>
                    <td><?php echo $row1['productID'] ?></td>
                    <td><?php echo $row1['qty'] ?></td>
                </tr>

                </table>


            <?

                       }
          }
                    }
                } 
}
             ?>

答案 1 :(得分:0)

select orderid, productid, sum(qty)
from productOrders
group by orderid, productid

将为您提供布局......

OrderID | ProductID | Qty
1       | 5         | 1
1       | 2         | 1
1       | 6         | 1
1       | 4         | 1
2       | 9         | 1
2       | 5         | 2
2       | 6         | 1

然后循环遍历每一行并根据需要在PHP中显示