How to write a select statement inside another select in SQL - mysql

Can anyone tell me what is wrong with this query?
it gives a syntax error near the 2nd select
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;

looks like you are missing a comma after MAX(h.edition)
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
besides the comma, you are selecting two fields in your subquery
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT preview FROM title_history WHERE idtitle_history = MAX(h.idtitle_history)),
(SELECT [file] FROM title_history WHERE idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;

Adding to bluefeet's answer, you may want to check for reserved words. "File" for example is a reserved word in sql server.

Alias it as a virtual table. Change something like
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder) as virtual_column_alias;
Check this out. Hope this will work.

Related

SQL Join gives wrong results (creates duplicates)

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

Ho to get last item in mysql using max()

I want to get the last item as result using max(), but i'm just getting the first item even if im using max()
Here's the SQL code:
SELECT r.correct, r.items, r.percentage,MAX(r.date_taken) as date_taken,
u.username,u.FN, u.user_course_type,
IFNULL(u.user_major_type,'N/A') as user_major_type,u.level_name,
u.section_name
FROM bcc_fs_exam_result r
INNER JOIN
(SELECT u.id_user, u.username, CONCAT(u.lastname,', ',u.firstname) as FN,
c.user_course_type, m.user_major_type, l.level_name, s.section_name
FROM bcc_fs_user u
LEFT JOIN bcc_fs_user_course c on c.id_user_course = u.id_user_course
LEFT JOIN bcc_fs_user_major m on m.id_user_major = u.id_user_major
LEFT JOIN bcc_fs_group_level l ON l.id_level = u.id_level
LEFT JOIN bcc_fs_group_section s ON s.id_section = u.id_section
) u ON r.id_user = u.id_user WHERE r.id_exam = 5 GROUP BY r.id_user
TIA
What I take from your question is that you want to get the "correct", "items", "percentage" ect. columns of the row in bcc_fs_exam_result which has the last or first date.
If that's correct then you can filter bcc_fs_exam_result by first finding what is the min or max date by for each id_user then join that back on the exam results table.
SELECT
r.correct,
r.items,
r.percentage,
r.date_taken,
u.username,
u.FN,
u.user_course_type,
IFNULL(u.user_major_type,'N/A') as user_major_type,
u.level_name,
u.section_name
FROM bcc_fs_exam_result r
INNER JOIN (
SELECT u.id_user,
u.username,
CONCAT(u.lastname,', ',u.firstname) as FN,
c.user_course_type,
m.user_major_type,
l.level_name,
s.section_name
FROM bcc_fs_user u
LEFT JOIN bcc_fs_user_course c on c.id_user_course = u.id_user_course
LEFT JOIN bcc_fs_user_major m on m.id_user_major = u.id_user_major
LEFT JOIN bcc_fs_group_level l ON l.id_level = u.id_level
LEFT JOIN bcc_fs_group_section s ON s.id_section = u.id_section
) u ON r.id_user = u.id_user
INNER JOIN (
SELECT
id_user, max(r.date_taken) as last_date_taken
FROM bcc_fs_exam_result
GROUP BY id_user
) as lastdate ON lastDate.id_user = r.id_user and r.date_taken = lastdate.last_date_taken
which could be more simply written as :
SELECT
r.correct,
r.items,
r.percentage,
r.date_taken,
u.username,
CONCAT(u.lastname,', ',u.firstname) as FN,
c.user_course_type,
IFNULL(m.user_major_type,'N/A') as user_major_type,
l.level_name,
s.section_name
FROM bcc_fs_exam_result r
INNER JOIN (
SELECT
id_user, max(r.date_taken) as last_date_taken
FROM bcc_fs_exam_result
GROUP BY id_user
) as lastdate ON lastDate.id_user = r.id_user and r.date_taken = lastdate.last_date_taken
INNER JOIN bcc_fs_user u on r.id_user = u.id_user
LEFT JOIN bcc_fs_user_course c on c.id_user_course = u.id_user_course
LEFT JOIN bcc_fs_user_major m on m.id_user_major = u.id_user_major
LEFT JOIN bcc_fs_group_level l ON l.id_level = u.id_level
LEFT JOIN bcc_fs_group_section s ON s.id_section = u.id_section
You have assumed that id_user + date_taken is a surrogate key of bcc_fs_exam_result which you should probably enforce with a constraint if at all possible. Otherwise it looks from your sample data that the order of the unique id column id_result follows the date_takenso you might be better to use Max(id_result) rather than Max(date_taken). That would avoid returning duplicate rows for one id_user where two rows of bcc_fs_exam_result have the same taken_date and `id_user.

Mysql REGEXP 2 words -- Same as AND LIKE

I have
SELECT p.*, gc.*, g.*, m.*, b.*
FROM (products AS p)
LEFT JOIN merchants AS m
ON m.merchantId = p.merchantId
LEFT JOIN brands AS b
ON b.brand = p.brand
LEFT JOIN groups_content gc
ON p.brand = gc.brandsSelect
LEFT JOIN groups g
ON g.group_id = gc.group_id
WHERE `p`.`percentOff` > gc.percent_off
AND `g`.`group_active` = 1
AND `p`.`price_sale` BETWEEN gc.price_min
AND gc.price_max
AND `gc`.`group_content_id` = '180'
AND `p`.`keyword` LIKE '%women%' AND `p`.`keyword` LIKE '%jacket%'
AND `p`.`status` = 1
ORDER BY p.price_sale ASC
this return me 158 results
Also I have
SELECT p.*, gc.*, g.*, m.*, b.*
FROM (products AS p)
LEFT JOIN merchants AS m
ON m.merchantId = p.merchantId
LEFT JOIN brands AS b
ON b.brand = p.brand
LEFT JOIN groups_content gc
ON p.brand = gc.brandsSelect
LEFT JOIN groups g
ON g.group_id = gc.group_id
WHERE `p`.`percentOff` > gc.percent_off
AND `g`.`group_active` = 1
AND `p`.`price_sale` BETWEEN gc.price_min
AND gc.price_max
AND `gc`.`group_content_id` = '180'
AND `p`.`keyword` REGEXP 'women.+jacket'
AND `p`.`status` = 1
ORDER BY p.price_sale ASC
This should return me same result like previous. But returns me just 17 results. What I am doing wrong?
----------
AFTER MANY SEARCHES here it is the right REGEXP
AND p.`keyword` REGEXP '^(.+jacket.+women.+)|^(.+women.+jacket.+).*$'
Your regex and like are not equivalent statements:
CREATE TABLE tab(keyword VARCHAR(100));
INSERT INTO tab(keyword)
VALUES ('jacket for women');
SELECT *
FROM tab p
WHERE `p`.`keyword` LIKE '%women%' AND `p`.`keyword` LIKE '%jacket%';
-- jacket for women
SELECT *
FROM tab p
WHERE p.`keyword` REGEXP 'women.+jacket';
-- (empty)
SqlFiddleDemo
"woman" anywhere in string and "jacket" anywhere in string
vs.
"woman" at the beginning, then any characters then "jacket" at the end
EDIT:
But How do I get -- "woman" anywhere in string and "jacket" anywhere
in string --- using regular expression?
One way is to use:
SELECT *
FROM tab
WHERE keyword REGEXP '.*women.*'
AND keyword REGEXP '.*jacket.*';
I am sure there exists one regex for this case.

Counting groups of 3? Possible?

I have the following query that is selecting groups of entries of 3 that match and don't exist in the second table.
I need to find a way to return via 'count_result' the count of the number of groups found, not individual entry ids as below.
How can I achieve this?
SELECT COUNT(sub.entry_id) as count_result
FROM exp_submissions AS sub
LEFT JOIN exp_judging_portfolios AS jud1 ON sub.entry_id = jud1.entry_id_1
LEFT JOIN exp_judging_portfolios AS jud2 ON sub.entry_id = jud1.entry_id_2
LEFT JOIN exp_judging_portfolios AS jud3 ON sub.entry_id = jud1.entry_id_3
WHERE jud1.entry_id_1 IS NULL
AND jud2.entry_id_2 IS NULL
AND jud3.entry_id_3 IS NULL
AND sub.member_group = 6
AND sub.type_id = 1
GROUP BY sub.member_id, sub.portfolio_number
HAVING count(sub.portfolio_number) = 3
No subquery necessary.
SELECT COUNT(DISTINCT(sub.member_id, sub.portfolio_number)) as count_result
FROM exp_submissions AS sub
LEFT JOIN exp_judging_portfolios AS jud1 ON sub.entry_id = jud1.entry_id_1
LEFT JOIN exp_judging_portfolios AS jud2 ON sub.entry_id = jud1.entry_id_2
LEFT JOIN exp_judging_portfolios AS jud3 ON sub.entry_id = jud1.entry_id_3
WHERE jud1.entry_id_1 IS NULL
AND jud2.entry_id_2 IS NULL
AND jud3.entry_id_3 IS NULL
AND sub.member_group = 6
AND sub.type_id = 1
GROUP BY sub.member_id, sub.portfolio_number
HAVING count(sub.portfolio_number) = 3
Use your query as the source for another query that just counts the results:
SELECT COUNT(*) FROM (
-- YOUR QUERY GOES HERE --
) AS t

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