0

我正在制作发票脚本,但是当我获取它们时,我的查询多次返回我的条目。

这是我的代码:

$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 个条目。

安尼坚韧?

4

3 回答 3

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";
于 2012-02-22T14:19:56.627 回答
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 中删除该表。

于 2012-02-22T14:20:14.880 回答
0

它为每个客户返回一行,因为客户表中的条目根本不受任何限制。我不确定您的表架构,但您应该添加以下内容:

AND c.CustomerID = o.CustomerID

到你的 WHERE 子句。

于 2012-02-22T14:21:42.240 回答