2016-02-21 115 views
0

我有一个这样的表在我的数据库只选择1个不同的列 - SQL

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,但每个订单ID仅输出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 
     } 
    } 
?> 
+4

“正常”认同ch将按照有序行从表中获取数据,然后在应用程序级进行重新格式化。 –

+1

哪个RDBMS?标签“sql”不是很多...而btw:你的昵称是 - uhm - 不是很专业...... – Shnugo

+1

@Shnugo看着他们的代码(函数),它是MySQL。编辑:我为其添加了标签。 –

回答

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> 


      <? 

         } 
      } 
        } 
       } 
} 
      ?> 
+0

嗨@TsvetilinBoynovski谢谢你的尝试,但是这为$ row1变量的每一行输出标题 – Sexpanther

+0

@Sexpanther你能告诉我确切的输出吗? –

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

,这将给你的布局......

然后根据需要在PHP

刚刚经历的每一行和显示环
OrderID | ProductID | Qty 
1  | 5   | 1 
1  | 2   | 1 
1  | 6   | 1 
1  | 4   | 1 
2  | 9   | 1 
2  | 5   | 2 
2  | 6   | 1