SQL Join gives wrong results (creates duplicates) - mysql

I have a problem with my SQL join query. I have looked up other suggested answers and tried to apply it to my query, but it doesn't seem to be working.
I have this query:
SELECT SUM(p.quantity)
FROM stocktake_scans p
LEFT JOIN (
SELECT stocktake_area_id
FROM stocktake_areas
WHERE stocktake_id =8592 AND area_checked = 1
)d ON d.stocktake_area_id = p.stocktake_area_id
LEFT JOIN (
SELECT user_id
FROM stocktake_scan_edit
WHERE user_id =46521
)e ON e.user_id = p.stocktake_staff_id
WHERE p.stocktake_staff_id = 46521
And it gives me a result of 42, while I should get only 6. What is missing from the query?

I think you may have extra records with the same ID in your joined table that is where you are getting multiple rows returned from which is then calculating wrong in your sum, please try the below.
SELECT SUM(p.quantity) FROM stocktake_scans p LEFT JOIN ( SELECT distinct stocktake_area_id FROM stocktake_areas WHERE stocktake_id =8592 AND area_checked = 1 )d ON d.stocktake_area_id = p.stocktake_area_id LEFT JOIN ( SELECT distinct user_id FROM stocktake_scan_edit WHERE user_id =46521 )e ON e.user_id = p.stocktake_staff_id WHERE p.stocktake_staff_id = 46521

Related

duplicates in mysql full join

I have two tables and I want to put them together and dont want to get the same id, instead I want to have the rows with the value and not with the null values - if there is an id with values.
This is my query
(SELECT users_antworten.user,
users_antworten.antwort,
profilfragen.id,
profilfragen.frage,
profilfragen.status,
profilfragen.aktiviert
FROM users_antworten
right JOIN profilfragen ON users_antworten.frage = NULL
WHERE profilfragen.aktiviert = 1
group by profilfragen.id
)
UNION
(SELECT users_antworten.user,
users_antworten.antwort,
profilfragen.id,
profilfragen.frage,
profilfragen.status,
profilfragen.aktiviert
FROM users_antworten
LEFT JOIN profilfragen ON users_antworten.frage = profilfragen.id
WHERE profilfragen.aktiviert = 1 AND users_antworten.user = 6
group by profilfragen.id
)
Thank you!
Finally after hours :-) I've got it:
(select null as user,
null as antwort,
p.id,
p.frage,
p.status,
p.aktiviert
FROM profilfragen p
WHERE not exists
( SELECT null
FROM users_antworten u
WHERE u.frage = p.id AND u.user=6
)
)
UNION
(SELECT u.user,
u.antwort,
p.id,
p.frage,
p.status,
p.aktiviert
FROM users_antworten u left join profilfragen p on p.id = u.frage WHERE u.user= :id
)

Mysql Select unique record based on multiple columns and display only group and sum amount

Hi I am trying to query a table that conatains multiple duplicates on Code,Amount and Status How will I do this if I only one to get a result group according to the client_group name and get the sum of amount under that group
SELECT `client`.`client_group`
, FORMAT(SUM(`Data_result`.`Data_result_amount` ),2) as sum
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
GROUP BY `client`.`client_group`
Result of said query:
Table
Try to distinct before run the 'sum' check whether this solve your problem
SELECT `client_group` , FORMAT(SUM(`Data_result_amount` ),2) as sum from (
SELECT DISTINCT `client`.`client_group` , `Data_result`.`Data_result_amount`
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
) T
GROUP BY `client_group`
you can check the query here http://sqlfiddle.com/#!9/36a3f8/6

Replacing sub query with join in mysql

I have a mysql query like...
SELECT OrderTransaction.buyer, OrderTransaction.parent_id
FROM order_transactions as OrderTransaction
INNER JOIN (
SELECT buyer
FROM order_transactions as dy
left join orders as ebay on ebay.id=dy.parent_id
where ebay.status='0' and dy.parent_id IN (
SELECT parent_id
FROM order_shipping_details as ds
left join orders as ebays on ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1
) and ebay.combined=0
group by dy.buyer
) dup ON dup.buyer=OrderTransaction.buyer
left join orders as ebay on ebay.id=OrderTransaction.parent_id
where ebay.market_type!='shopclue' and ebay.status='0' and ebay.combined=0
I need to optimize this query and want to remove the inner select with joins.
Any help would be appreciated. Thanks in advance.
Try this code below might be running faster than the one u currently using:
DROP TEMPORARY TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1;
SELECT buyer
FROM order_transactions AS dy
LEFT JOIN orders AS ebay ON ebay.id=dy.parent_id
WHERE ebay.status='0'
AND dy.parent_id
IN (
SELECT parent_id
FROM order_shipping_details AS ds
left join orders AS ebays ON ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1)
AND ebay.combined= '0'
;
SELECT
OrderTransaction.buyer,
OrderTransaction.parent_id
FROM order_transactions AS OrderTransaction
INNER JOIN temp1 AS tmp ON tmp.buyer = OrderTransaction.buyer
LEFT JOIN orders AS ebay ON ebay.id = OrderTransaction.parent_id
WHERE ebay.market_type! = 'shopclub' AND ebay.status = '0' and ebay.combined = '0'
Please let me know if you have any questions!

SQL query wrong result

i have this query:
SELECT `completed`.`ID` AS `ID`,`completed`.`level` AS `level`,`completed`.`completed_in` AS `completed_in`, COUNT(1) AS `right_answers_num`
FROM `completed`
INNER JOIN `history` ON `history`.`ID` = `completed`.`ID`
INNER JOIN `questions` ON `questions`.`ID` = `history`.`question`
WHERE `completed`.`student_id` = '1' AND `questions`.`answer` = `history`.`answer`
GROUP BY `completed`.`ID`
ORDER BY `completed`.`completed_in` DESC
what i need is to get info of each test in completed table (id,level,completed_in,right_answer_num)
the problem with that query is that if there is no one right answer(history.answer = questions.answer) then it doesn't return the row, while it should return the row(id,level,completed_in) and the right_answer_num(counter) should be zero..
please help me,, thanks ahead.
SELECT
completed.ID AS ID,
completed.level AS level,
completed.completed_in AS completed_in,
COUNT(questions.answer) AS right_answers_num
FROM completed
INNER JOIN history ON history.ID = completed.ID
LEFT JOIN questions ON questions.ID = history.question AND questions.answer = history.answer
WHERE
completed.student_id = '1'
GROUP BY
completed.ID
ORDER BY completed.completed_in DESC
use a LEFT OUTER JOIN intead of an INNER JOIN.
The second inner join is what's causing rows with no record in the questions table to be omitted. An inner join will only return rows that have data in all corresponding tables. Change the second inner join to a left join like so:
SELECT
completed.ID AS ID,
completed.level AS level,
completed.completed_in AS completed_in,
COUNT(questions.answer) AS right_answers_num
FROM completed
INNER JOIN history ON history.ID = completed.ID
LEFT JOIN questions ON questions.ID = history.question
WHERE completed.student_id = 1
GROUP BY completed.ID
ORDER BY completed.completed_in DESC

MySQL Query Optimisation

Looking for some help with optimising the query below. Seems to be two bottlenecks at the moment which cause it to take around 90s to complete the query. There's only 5000 products so it's not exactly a massive database/table. The bottlenecks are SQL_CALC_FOUND_ROWS and the ORDER BY statement - If I remove both of these it takes around a second to run the query.
I've tried removing SQL_CALC_FOUND_ROWS and running a count() statement, but that takes a long time as well..
Is the best thing going to be to use INNER JOIN's (which I'm not too familiar with) as per the following Stackoverflow post? Slow query when using ORDER BY
SELECT SQL_CALC_FOUND_ROWS *
FROM tbl_products
LEFT JOIN tbl_link_products_categories ON lpc_p_id = p_id
LEFT JOIN tbl_link_products_brands ON lpb_p_id = p_id
LEFT JOIN tbl_link_products_authors ON lpa_p_id = p_id
LEFT JOIN tbl_link_products_narrators ON lpn_p_id = p_id
LEFT JOIN tbl_linkfiles ON lf_id = p_id
AND (
lf_table = 'tbl_products'
OR lf_table IS NULL
)
LEFT JOIN tbl_files ON lf_file_id = file_id
AND (
file_nameid = 'p_main_image_'
OR file_nameid IS NULL
)
WHERE p_live = 'y'
ORDER BY p_title_clean ASC, p_title ASC
LIMIT 0 , 10
You could try reducing the size of the joins by using a derived table to retrieve the filtered and ordered products before joining. This assumes that p_live, p_title_clean and p_title are fields in your tbl_products table -
SELECT *
FROM (SELECT *
FROM tbl_products
WHERE p_live = 'y'
ORDER BY p_title_clean ASC, p_title ASC
LIMIT 0 , 10
) AS tbl_products
LEFT JOIN tbl_link_products_categories
ON lpc_p_id = p_id
LEFT JOIN tbl_link_products_brands
ON lpb_p_id = p_id
LEFT JOIN tbl_link_products_authors
ON lpa_p_id = p_id
LEFT JOIN tbl_link_products_narrators
ON lpn_p_id = p_id
LEFT JOIN tbl_linkfiles
ON lf_id = p_id
AND (
lf_table = 'tbl_products'
OR lf_table IS NULL
)
LEFT JOIN tbl_files
ON lf_file_id = file_id
AND (
file_nameid = 'p_main_image_'
OR file_nameid IS NULL
)
This is a "stab in the dark" as there is not enough detail in your question.