I have this query:
SELECT
course_category.id AS languageId,
course_category.code AS languageCode,
course_category.name AS languageName,
(
SELECT
SUM(gradebook_result.score)
FROM
gradebook_result
JOIN
gradebook_evaluation ON gradebook_evaluation.id=gradebook_result.evaluation_id
JOIN
gradebook_category ON gradebook_category.id=gradebook_evaluation.category_id
WHERE
gradebook_category.course_code=course_category.code
) AS languageWordsTranslated
FROM
course_category
WHERE
course_category.code != 'GEN'
ORDER BY
name
ASC
The problem occurs inside the nested SELECT where I get an error referencing the course_category table from within the SELECT on line:
WHERE
gradebook_category.course_code=course_category.code
Giving error:
Unknown column 'course_category.code' in 'where clause'
I have done this query before with other projects the only difference is that this one has joins within it. Any ideas?
EDIT: I removed the joins and hardcoded:
WHERE
course_category.code = 'ARA'
Seems like the joins mess it up, any way to fix that??
Try to do it a bit different way, using subquery and joining to it:
SELECT
course_category.id AS languageId,
course_category.code AS languageCode,
course_category.name AS languageName,
t.total AS languageWordsTranslated
FROM
course_category
JOIN (
SELECT gradebook_category.course_code, SUM(gradebook_result.score) as total
FROM gradebook_result
JOIN gradebook_evaluation ON gradebook_evaluation.id=gradebook_result.evaluation_id
JOIN gradebook_category ON gradebook_category.id=gradebook_evaluation.category_id
GROUP BY gradebook_category.course_code
) t ON t.course_code = course_category.code
WHERE
course_category.code != 'GEN'
ORDER BY
name
ASC
Related
I'm trying to run a query on the result set of another query but getting errors which I cannot understand. I'm sure it's something small but I'm somehow missing it. This is the query:
SELECT
RLID,
NAME,
GROUP_CONCAT(SUBQUERY.Items SEPARATOR ', ') AS Items
FROM
(
SELECT
`rel_menu_item`.`ID` AS `RLID`,
`menu`.`Name` AS `Menu_Name`,
`item`.`Name` AS `Items`
FROM
`rel_menu_item`
JOIN
`menu` ON `menu`.`ID` = `rel_menu_item`.`Menu_ID`
JOIN
`item` ON `item`.`ID` = `rel_menu_item`.`Item_ID`
) AS SUBQUERY
GROUP BY
SUBQUERY.Name
Errors:
3 errors were found during analysis.
An expression was expected. (near "(" at position 90)
Unexpected token. (near "(" at position 90)
This type of clause was previously parsed. (near "SELECT" at position 95)
I found the errors. Here is the correct query:
SELECT
SUBQUERY.RLID,
SUBQUERY.Menu_Name,
GROUP_CONCAT(SUBQUERY.Items SEPARATOR ', ') AS Items
FROM
(
SELECT
rel_menu_item.ID AS RLID,
menu.Name AS Menu_Name,
item.Name AS Items
FROM
rel_menu_item
JOIN
menu ON menu.ID = rel_menu_item.Menu_ID
JOIN
item ON item.ID = rel_menu_item.Item_ID
) AS SUBQUERY
GROUP BY
SUBQUERY.Menu_Name
You should be writing this query without a subquery at all:
SELECT m.Id as RLID, m.Name as Menu_Name
GROUP_CONCAT(i.name SEPARATOR ', ') AS Items
FROM rel_menu_item rmi JOIN
menu m
ON m.ID = rmi.Menu_ID JOIN
item i
ON i.ID = rmi.Item_ID
GROUP BY m.Id, m.Name;
Notes:
The subquery is not needed.
Table aliases make the query easier to write and to read.
It is better to use the column from the primary key table menu.id rather than from the references foreign key. It doesn't really make a difference with inner joins, but it does make a difference with outer joins; hence, it is a bad practice.
You should include all non-aggregated columns in the GROUP BY.
This almost seems like a scope issue- the select statement in the subquery doesn't recognize table 'candidate':
SELECT
candidate.id AS id,
candidate.image AS image,
candidate.name AS name,
candidate.party AS party,
player.order AS player_order,
c_pcts.pct AS pct
FROM `candidate`
INNER JOIN players player ON player.candidate_id = candidate.id
INNER JOIN lineups lineup ON player.lineup_id = lineup.id
INNER JOIN (
SELECT
pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE p.candidate_id = candidate.id
) c_pcts
WHERE lineup.id = '31'
ORDER BY player.order ASC
gives the error: "Unknown column 'candidate.id' in 'where clause'." If instead of "FROM candidate_pcts p" I put
FROM candidate_pcts p, candidate c
then it doesn't see 'p.weekly_game_id' ...huh?
Seems like I need to identify the 'candidate' table for the subquery somehow but everything I'm trying leads me only further astray. And I have tried a mess of things: order of the tables, explicitly identifying them everywhere i could think of, backticks. I should note that the nested subquery works like a charm. Here it is again:
SELECT
pct
FROM `candidate_pcts`
INNER JOIN weekly_game game ON candidate_pcts.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE candidate_pcts.candidate_id = '5'
with a hardcoded an id value there, of course. I can supply database structure if needed here, but this is long already. The 'weekly_game' table is simply a set of scores for each candidate each week and we only want the most recent week's score, thus the 'ORDER BY date DESC LIMIT 1' clause.
Thanks very much for your time.
Tables:
table candidate: {id, image, name, party}
table candidate_pcts: {id, candidate_id, pct, weekly_game_id}
table lineups: {id, date, user_id}
table players: {id,candidate_id,lineup_id,order}
table weekly_game: {id,date}
You are basically on the right track around the problem. In essence the nested sub-select does not know about candidate.id. It you break apart the query and just look at the sub-select in question:
SELECT
pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE p.candidate_id = candidate.id
You can see there is NO reference whatsoever in that query to the candidate table other than in your where clause, thus this is an unknown column.
Since a subselect is, in essence, made before the outer select that references it, the subselect must be a standalone, executable query.
Thanks to all, especially Mike for that excellent explanation. What I did was restructured the query like so:
SELECT
candidate.id AS id,
candidate.image AS image,
candidate.name AS name,
candidate.party AS party,
player.order AS player_order,
pcts.pct AS pct
FROM `candidate`
INNER JOIN players player ON player.candidate_id = candidate.id
INNER JOIN lineups lineup ON player.lineup_id = lineup.id
LEFT JOIN (
SELECT
p.candidate_id AS pct_id, pct AS pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
)
) pcts
ON pct_id = candidate.id
WHERE lineup.id = '$lineup_id'
ORDER BY player.order ASC
I have couple tables joined in MySQL - one has many others.
And try to select items from one, ordered by min values from another table.
Without grouping in seems to be like this:
Code:
select `catalog_products`.id
, `catalog_products`.alias
, `tmpKits`.`minPrice`
from `catalog_products`
left join `product_kits` on `product_kits`.`product_id` = `catalog_products`.`id`
left join (
SELECT MIN(new_price) AS minPrice, id FROM product_kits GROUP BY id
) AS tmpKits on `tmpKits`.`id` = `product_kits`.`id`
where `category_id` in ('62')
order by product_kits.new_price ASC
Result:
But when I add group by, I get this:
Code:
select `catalog_products`.id
, `catalog_products`.alias
, `tmpKits`.`minPrice`
from `catalog_products`
left join `product_kits` on `product_kits`.`product_id` = `catalog_products`.`id`
left join (
SELECT MIN(new_price) AS minPrice, id FROM product_kits GROUP BY id
) AS tmpKits on `tmpKits`.`id` = `product_kits`.`id`
where `category_id` in ('62')
group by `catalog_products`.`id`
order by product_kits.new_price ASC
Result:
And this is incorrect sorting!
Somehow when I group this results, I get id 280 before 281!
But I need to get:
281|1600.00
280|2340.00
So, grouping breaks existing ordering!
For one, when you apply the GROUP BY to only one column, there is no guarantee that the values in the other columns will be consistently correct. Unfortunately, MySQL allows this type of SELECT/GROUPing to happen other products don't. Two, the syntax of using an ORDER BY in a subquery while allowed in MySQL is not allowed in other database products including SQL Server. You should use a solution that will return the proper result each time it is executed.
So the query will be:
For one, when you apply the GROUP BY to only one column, there is no guarantee that the values in the other columns will be consistently correct. Unfortunately, MySQL allows this type of SELECT/GROUPing to happen other products don't. Two, the syntax of using an ORDER BY in a subquery while allowed in MySQL is not allowed in other database products including SQL Server. You should use a solution that will return the proper result each time it is executed.
So the query will be:
select CP.`id`, CP.`alias`, TK.`minPrice`
from catalog_products CP
left join `product_kits` PK on PK.`product_id` = CP.`id`
left join (
SELECT MIN(`new_price`) AS "minPrice", `id` FROM product_kits GROUP BY `id`
) AS TK on TK.`id` = PK.`id`
where CP.`category_id` IN ('62')
order by PK.`new_price` ASC
group by CP.`id`
The thing is that group by does not recognize order by in MySQL.
Actually, what I was doing is really bad practice.
In this case you should use distinct and by catalog_products.*
In my opinion, group by is really useful when you need group result of agregated functions.
Otherwise you should not use it to get unique values.
This is my mysql query
SELECT tm.MAGAZINE_ID, tm.MAGAZINE_NAME,tm.MAGAZINE_DESCRIPTION,pub.publisher_name,
tmi.COVER_PAGE_THUMB AS COVER_PAGE_VERTICAL,tmi.FROM_DATE AS ISSUE_DATE,
tm.html_flag AS HTML_EXIST,tm.CATEGORY_ID,tm.language_id,tm.is_free,tma.AppUrl,
(SELECT issue_id from tbl_magazine_issue WHERE magazine_id = 141
ORDER BY FROM_DATE DESC LIMIT 1) as temp_issue_id
FROM tbl_magazine_apps as tma
LEFT OUTER JOIN tbl_magazine_code as tmc ON tmc.Code = tma.AppsCode
LEFT OUTER JOIN `tbl_magazine` AS tm ON tmc.magazine_Id = tm.MAGAZINE_ID
JOIN `tbl_magazine_issue` AS tmi ON temp_issue_id = tmi.issue_id
LEFT OUTER JOIN mst_publisher AS pub ON tm.publisher_id=pub.publisher_id
WHERE
tmi.PUBLISH_STATUS IN(1,3)
AND tmi.`OS_SELECT` = '".$osType."'
AND tma.id IN (".$appIds.")
GROUP BY tm.MAGAZINE_ID
ORDER BY tmi.ISSUE_DATE DESC
but i got an error that
#1054 - Unknown column 'temp_issue_id' in 'on clause'
if any one know about this please help me. i am new to this
AFAIK The subquery belongs to the from part:
http://dev.mysql.com/doc/refman/5.7/en/from-clause-subqueries.html
So I would join the subquery.
Like:
SELECT a.a, b.b
FROM table1 as a
JOIN (SELECT b from table2) as b ON a.key = b.key;
As the message suggests, the column temp_issue_id is not in any of the following tables: tbl_magazine_apps, tbl_magazine, or tbl_magazine_issue. It is also not a variable in the environment.
Beyond that, it is pretty much impossible for anyone to figure out how to fix the problem without more knowledge about the data structure.
If I were to hazard a guess, based on the table names, that particular join would be:
JOIN `tbl_magazine_issue` AS tmi ON tm.magazine_id = tmi.magazine_id
because it makes sense to me that a magazine issue would be connect to a magazine. I have no idea what temp_issue_id is, though.
temp_issue_id give alias name for specifying this column i think it should be tm.issue_id
temp_issue_id is column's name as per the query. You need it to convert to table and use subsequent column in your SELECT clause.
While working on a system I'm creating, I attempted to use the following query in my project:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
WHERE topics.cat_id = :cat
GROUP BY topics.id
":cat" is bound by my PHP code as I'm using PDO. 2 is a valid value for ":cat".
That query though gives me an error: "#1241 - Operand should contain 1 column(s)"
What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can't figure out what the problem is.
Is there a simple fix to this, or another way to write my query?
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.
Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:
SELECT (p.column1, p.column2, p.column3) FROM table1 p WHERE p.column1 = 1;
And has to be:
SELECT p.column1, p.column2, p.column3 FROM table1 p WHERE p.column1 = 1;
Sounds silly, but it was causing this error and it took some time to figure it out.
This error can also occur if you accidentally use commas instead of AND in the ON clause of a JOIN:
JOIN joined_table ON (joined_table.column = table.column, joined_table.column2 = table.column2)
^
should be AND, not a comma
This error can also occur if you accidentally use = instead of IN in the WHERE clause:
FOR EXAMPLE:
WHERE product_id = (1,2,3);
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
FROM users
WHERE users.id = posts.posted_by)
...
I got this error while executing a MySQL script in an Intellij console, because of adding brackets in the wrong place:
WRONG:
SELECT user.id
FROM user
WHERE id IN (:ids); # Do not put brackets around list argument
RIGHT:
SELECT user.id
FROM user
WHERE id IN :ids; # No brackets is correct
This error can also occur if you accidentally miss if function name.
for example:
set v_filter_value = 100;
select
f_id,
f_sale_value
from
t_seller
where
f_id = 5
and (v_filter_value <> 0, f_sale_value = v_filter_value, true);
Got this problem when I missed putting if in the if function!
Another place this error can happen in is assigning a value that has a comma outside of a string. For example:
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column.
Separate it otherwise it will shows error.
I also have the same issue in making a company database.
this is the code
SELECT FNAME,DNO FROM EMP
WHERE SALARY IN (SELECT MAX(SALARY), DNO
FROM EMP GROUP BY DNO);