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
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.
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";
Related
I am having relational database and trying to execute following query up to 3 tables It is giving me correct results i.e. 248 records of students in institute id 910, but when I try to make a query having more than 3 tables it gives me 19000+ results.
SELECT *
FROM Student,StudentRegistration,RefStudentType,RefGender,SubjectCategory
WHERE Student.student_id=StudentRegistration.student_student_id
AND StudentRegistration.reg_student_type_std_type_id = RefStudentType.std_type_id
AND Student.student_gender_gender_id = RefGender.gender_id
AND StudentRegistration.reg_student_subjectCat_sub_cat_id=SubjectCategory.sub_cat_id
AND Student.student_institute_inst_id=910;
`
Tried with JOIN as well but same 19000+ records incorrect results
SELECT * FROM Student INNER JOIN StudentRegistration ON student_id=student_student_id INNER JOIN RefReligion ON RefReligion.religion_id=Student.student_religion_religion_id INNER JOIN RefStudentType ON RefStudentType.std_type_id=StudentRegistration.reg_student_type_std_type_id WHERE student_institute_inst_id=910;
Any solution, query logical errors or something new
I think this is due to having several records for one data. For example, there might be several records in the SubjectCategory table for id = '910'
It is best to use left/right/inner/outer joins without using from tbl1, tbl2
What I suggest is to check the tables one by one with the id.
I have 2 tables:
DAY_INTERVALS (interval_start)
ORDERS (client_id, order_time, order_total_price)
I want to display all the days in the DAY_INTERVAL table against the ORDERS table. Below is the SQL that I am using.
SELECT DATE_FORMAT(order_time,'%Y-%m-%d') as dates, COALESCE(SUM(order_total_price), 0) AS sales
FROM time_intervals ti
LEFT JOIN orders o
ON DATE(o.order_time) = ti.interval_start AND (o.client_id = 157 or o.client_id is NULL)
GROUP BY DAY(o.order_time)
It is not displaying the NULL results of the days which don't exist in the orders table. The query should display all the days regardless if it is in the orders table.
I have looked at similar questions but the query above is what I come up with based on the other solutions.
Any advise would be much appreciated.
If you get rid of AND (o.client_id = 157 or o.client_id is NULL) it would give you the data set you're looking for.
You're effectively executing the "Left Excluding JOIN" from this article:
http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
The only difference is you're executing it from your ON clause instead of the WHERE clause.
$sql = mysql_query("SELECT totals.*, sum(totals.payments) as total_payments
FROM totals
INNER JOIN users
GROUP BY totals.idseller;");
When i add the INNER JOIN the sum value is changed. Why?
In my SQL table i have one record in totals width this value: 8943.09 but when i do the some the result is giving me this value: 44715.45
What i am doing wrong?
$sql = mysql_query("SELECT totals.*, sum(totals.payments) as total_payments FROM totals
INNER JOIN users ON totals.idseller = users.idseller
GROUP BY users.UserName;");
Use this Hope this will help you.
When you INNER JOIN to another table, the returned data set is modified to only include rows that exist in both tables. In this case it is likely that there are rows in 'totals' that do not have a matching row in users - either the totals.idseller field might accept null values, or data has become orphaned when matching users have been deleted or edited.
If you want all data in 'totals' regardless of matching user you would user a LEFT JOIN instead in ms-sql, I suspect a similar approach will work in my-sql
You should give an "on" based on the ids. Such as like
inner join users on users.id = totals.idseller
Otherways the sql server will combine all possible rows in the tables, which is most cases not what you wish.
Because when you are adding inner join in your SQL Query, it means you are selecting the data which is common in both the tables.
EX:
SELECT * FROM TABLE_A
INNER JOIN TABLE_B
ON TABLE_A.ID = TABLE_B.ID
If you are joining users table which contains 5 records. By joining table, as there is no any column mapping, this sum-up 5 times and this is reason for showing different values.
Please let me know something wrong in it.
Thanks,
Umehs
First of all, I have no control over the database structure, etc.
I need to use PHP to retrieve records by state and name but all the data is in multiple tables. Basically I need to try and understand how to get these two queries combined so that they do not run so slow.
First I get my record ID's in PHP. (Lets assume $query returns an array of IDs)
table_products = A bunch of products
$query = "SELECT id,name FROM table_products WHERE name = '".$name."';";
Than I need to iterate through these records (NOTE : There can be A LOT) and figure out where these IDs reside in another two tables that has the location information of where they could be at.
table_places = a table with a bunch of locations
link_table = Contains the relationships between product and location
$state = "somestate";
foreach($query as $row)
{
$query_two = "SELECT table_places.name, table_places.id, table_places.state, link_table.place_id, link_table.product_id
FROM table_places
INNER JOIN link_table
ON table_places.id = link_table.place_id
WHERE table_places.state = '".$state."' AND link_table.product_id = '".$row->id."';";
}
God I hope this made sense. I am no query guru so if I could get assistance in optimizing this to run faster, I would be grateful.
The pain is here:
foreach($query as $row) <<--- you are pinging the DB to death.
Combine the two queries:
SELECT
pl.name, pl.id, pl.state,
l.place_id, l.product_id,
pr.name
FROM table_places pl
INNER JOIN link_table l ON (pl.id = l.place_id)
INNER JOIN table_products pr ON (l.product_id = pr.id)
WHERE pr.name = '$name'
AND pl.state = '$state'
ORDER BY pr.name, pl.state
Make sure you put indexes on all fields used in the ON clauses and the where clauses.
You can join more than two tables in one query. Untested query would be something like;
SELECT * FROM table_products AS prod LEFT JOIN (link_table AS link, table_places AS places)
ON (prod.id=link.id AND prod.id=places.id)
WHERE some_field='some_value'
This will definitely get you some performance boost, as one query is most of times a lot faster than number-of-records query's (as you now loop through the records and query the db once per record)
The answer is simple: no control over database structure - no way to optimize.
As the indexing being the cornerstone of query optimization and you obviously need access to table structure to add one.
I am trying to export all the products and some info about them from my mySQL so I wrote the following query
SELECT * FROM products
JOIN descriptions
ON products.product_id = descriptions.product_id
JOIN category_descriptions
ON categories.category_id = descriptions.category_id
for a reason, it outputs every product four times. Can anyone help me to find out why?
Update: There are only 122 products in cscart_products. The results after this query are 488.
Add GROUP BY cscart_products.product_id
Your query:
SELECT * FROM cscart_products
JOIN cscart_product_descriptions
ON cscart_products.product_id = cscart_product_descriptions.product_id
JOIN cscart_products_categories
ON cscart_products.product_id = cscart_products_categories.product_id
JOIN cscart_category_descriptions
ON cscart_products_categories.category_id = cscart_category_descriptions.category_id
GROUP BY cscart_products.product_id
SELECT DISTINCT solves your problem: http://www.sql-tutorial.com/sql-distinct-sql-tutorial/
Try left join.
http://phpweby.com/tutorials/mysql/32
Either a product has several descriptions or categories, or a category has several descriptions, or there are duplicate entries on your database.
Can anyone help me to find out why?
Here's a clue. The wildcard character you are using is used to display all columns/fields. There are four tables used in the query. Now we can't be certain of anything as the database schemas haven't been posted.