Question

I am running this query

$sql6 = "SELECT RECIPE.Price, RECIPE.Name FROM ORDERRECI, ORDERS, RECIPE WHERE ORDERRECI.OrderID = $orderID AND ORDERRECI.RecipeID = RECIPE.RecipeID";        
$results = mysqli_query($con, $sql6);
while ($row=mysqli_fetch_assoc($results))
{
    $calcC+= $row['Price'];
    echo $calcC.$row['Name']."<br />";
}
return $calcC;

The query Runs fine I'm getting the right values But I'm getting them 9 times.( I checked via the echo). I checked the Database they are only in there once. I tried using Distinct but because the customer can pick the same side multiple times they would get an inaccurate result (tested. Can anyone explain why. Would using join help. My teacher favors where(Don't know why) but that's why I use it
EDIT: I Recipe and Orders have a many-to-many relationship ORDERRECI is the referential table. I am trying to calculate the Total Cost of an order. I just tried inner join but it still duplicated and this time it duplicated 14 times

Was it helpful?

Solution

FROM ORDERRECI, ORDERS, RECIPE here you are doing a Cartesian product with the 3 tables, which means, each row from each table will be paired with each row from every other table from the FROM list. I don't know what was your goal with the query, but that is whats happening.

OTHER TIPS

Try adding this to your query

GROUP BY RECIPE.Name

For each row in ORDERRECI you create a merged row with each one of the rows in ORDERS and the same goes for RECIPE.

You should use LEFT JOIN. Read about SQL join types here

I ended up with this statement. I Needed the general join of the tables. then use where to narrow it down. Thanks for the help in figuring it out
$sql = "SELECT RECIPE.Price FROM ORDERRECI INNER JOIN ORDERS ON ORDERRECI.OrderID = ORDERS.OrderID INNER JOIN RECIPE ON ORDERRECI.RecipeID = RECIPE.RecipeID WHERE ORDERS.OrderID = $orderID";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top