Mysql duplica i risultati
-
29-10-2019 - |
Domanda
Sto creando uno script per la fattura ma la mia query restituisce tutte le mie voci più volte quando le recupero.
questo è il mio codice:
$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>';
}
questa è, una parte, di ciò che restituisce.
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
mentre potrebbe restituire solo 3 voci.
anny tosta?
Soluzione
Hai un join cartesiano:
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
Devi includere un join per i clienti o eliminare quella tabella dall'SQL.
Altri suggerimenti
Ti manca un join per la tabella dei clienti.Invece di non utilizzare alcuna colonna dalla tabella del cliente, puoi tranquillamente rimuovere la tabella dalla clausola 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";
Restituisce una riga per ogni cliente, perché le voci dalla tabella dei clienti non sono vincolate in alcun modo.Non sono sicuro dello schema della tua tabella, ma dovresti aggiungere qualcosa come:
AND c.CustomerID = o.CustomerID
alla tua clausola WHERE.