2012-02-22 55 views
0

我正在製作發票腳本,但我的查詢返回我的項目多次,當我拿他們。Mysql duplecating結果

這是我的代碼:

$query  = " SELECT d.Quantity, d.ProductID, p.ProductName, d.UnitPrice, d.Discount 
          FROM customers AS c, orders AS o, order_details AS d, products AS p 
          WHERE o.OrderID = '10248' 
          AND o.OrderID = d.OrderID 
          AND d.ProductID = p.ProductID 
         "; 

     $result  = mysql_query($query); 

     $table  = ''; 

     while($row = mysql_fetch_assoc($result)){ 
      $table .= '<tr>'; 
      $table .= '<td>' . $row['Quantity'] . '</td>'; 
      $table .= '<td>' . $row['ProductID'] . '</td>'; 
      $table .= '<td>' . $row['ProductName'] . '</td>'; 
      $table .= '<td>' . $row['UnitPrice'] . '</td>'; 
      $table .= '<td>' . $row['Discount'] . '</td>'; 
      $table .= '<td>' . (100 - $row['Discount'])/100 * $row['UnitPrice'] . '</td>'; 
      $table .= '</tr>'; 
     } 

這是一個部分,什麼返回。

Quantity ProductID ProductName  UnitPrice Discount Subtotal 
12 11 Queso Cabrales 14.0000 0 14 
10 42 Singaporean Hokkien Fried Mee 9.8000 0 9.8 
5 72 Mozzarella di Giovanni 34.8000 0 34.8 
12 11 Queso Cabrales 14.0000 0 14 
10 42 Singaporean Hokkien Fried Mee 9.8000 0 9.8 
5 72 Mozzarella di Giovanni 34.8000 0 34.8 
12 11 Queso Cabrales 14.0000 0 14 
10 42 Singaporean Hokkien Fried Mee 9.8000 0 9.8 
5 72 Mozzarella di Giovanni 34.8000 0 34.8 
12 11 Queso Cabrales 14.0000 0 14 
10 42 Singaporean Hokkien Fried Mee 9.8000 0 9.8 
5 72 Mozzarella di Giovanni 34.8000 0 34.8 

雖然它只能返回3個條目。

anny toughts?

+0

瞭解如何連接多個表格。有多種方法可以執行連接,一種方法是將每個元素相互組合,反之亦然(交叉表或交叉連接,也是笛卡爾連接,用於缺少連接),這就是爲什麼你會得到那很多結果。參見[使用MySQL,加入](http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php) – hakre 2012-02-22 14:23:46

回答

1

你有一個笛卡兒連接:

SELECT d.Quantity, 
     d.ProductID, 
     p.ProductName, 
     d.UnitPrice, 
     d.Discount 
FROM **customers AS c,** 
     orders AS o, 
     order_details AS d, 
     products AS p 
WHERE o.OrderID = '10248' 
AND o.OrderID = d.OrderID 
AND d.ProductID = p.ProductID 

您需要包括一個連接到客戶,或從SQL中刪除該表。

+0

Tnx DB,總是忘記從查詢中刪除。在之前有客戶信息但刪除了它。我沒有看到那個人的身影。 TNX! – Roeliee 2012-02-22 14:23:12

+0

沒問題,很樂意幫忙 – 2012-02-22 14:26:58

1

您缺少客戶表的加入。而是你不使用從客戶表中的任何列,您可以安全地從FROM條款刪除表:

$query = "SELECT d.Quantity, d.ProductID, p.ProductName, d.UnitPrice, d.Discount 
       FROM orders AS o, order_details AS d, products AS p 
        WHERE o.OrderID = '10248' 
        AND o.OrderID = d.OrderID 
        AND d.ProductID = p.ProductID"; 
0

它爲每個客戶返回一行,因爲客戶表中的條目根本沒有任何限制。我不知道你的表格模式,但你應該添加類似:

AND c.CustomerID = o.CustomerID 

到你的WHERE子句。