Second Subquery reference to parent-parent query: column not found - mysql

Is there a limit of subquerys where the referencing outer column is working on?
I tried this query:
SELECT
`userouter`.`id` AS `user_id`
FROM
`users` AS `userouter`
WHERE
123456 = (
SELECT
SUM(`tmp`.`sum`) AS `sum_total`
FROM
(
SELECT
SUM(`invoiceposition`.`number` * `invoiceposition`.`amount`) AS `sum`
FROM
`invoices` AS `invoice` INNER JOIN
`invoicepositions` AS `invoiceposition` ON
`invoice`.`id` = `invoiceposition`.`invoice`
WHERE
`invoice`.`user` = `userouter`.`id`
GROUP BY
`invoice`.`id`
) AS `tmp`
)
GROUP BY
`userouter`.`id`
And i get Error Code: 1054. Unknown column 'userouter.id' in 'where clause'
How can i reference the userouter.id in the sub-sub query?

As it seems in a normal way not possible to resolve the problem (double nested subquery reference to outer query), i now solved the problem by creating a mysql function with the user id as parameter.
hope this will help other searchers

Remove the double nesting.
SELECT
`userouter`.`id` AS `user_id`
FROM
`users` AS `userouter`
LEFT JOIN (
SELECT
`invoice`.`user` as `user_id`, SUM(`invoiceposition`.`number` * `invoiceposition`.`amount`) AS `sum`
FROM
`invoices` AS `invoice` INNER JOIN
`invoicepositions` AS `invoiceposition` ON
`invoice`.`id` = `invoiceposition`.`invoice`
WHERE
`invoice`.`user` = `userouter`.`id`
GROUP BY
`invoice`.`id`
) AS `tmp`
ON `tmp`.`user_id` = `userouter`.`id`
WHERE
123456 = `userouter`.`id`
GROUP BY
`userouter`.`id`

Related

MySQL Query, (access mainquery from subquery)

I have a problem that I need a WHERE clause in a subquery that depends on the results of the main Query, otherwise my results would be wrong and the query takes too long / is not executeable.
The circumstances that I need this query to create a view which I need for a search server support the problem that I cannot split this into two queries, nor process it with a script dynamically.
The problem occurs with the following query:
SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
FROM
(
SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
FROM `rating` r
INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
WHERE `r`.`seminar_id` = `s`.`id`/* <- Here is my problem, this is inacessible */
GROUP BY `r`.`seminar_id`
) AS sub,
`seminar` s
INNER JOIN `date` d
ON `s`.`id` = `d`.`seminar_id`
INNER JOIN `date_unit` du
ON `d`.`id` = `du`.`date_id`
LEFT JOIN `seminar_subject` su
ON `s`.`id` = `su`.`seminar_id`
LEFT JOIN `subject` suj
ON `su`.`subject_id` = `suj`.`id`
INNER JOIN `user` u
ON `s`.`user_id` = `u`.`id`
INNER JOIN `company` c
ON `u`.`company_id` = `c`.`id`
GROUP BY `du`.`date_id`, `sub`.`seminar_id`
This query should calculate a total rate out of ratings for each Seminar.
However my ratings are stored in my "rating" table and should be processed live.
(Sidenote: If you wonder about all the joins: This query has alooot more SELECT'ed fields, I just removed them because they are not nesessary to solve the problem and to make the query look less complicated [I know it still is >.>]...)
The reason is that I want this results to be sortable by my search engine later depending
on the users sort parameters, thatswhy I need it inside this query.
The problem itself is pretty obvious:
ERROR 1054 (42S22): Unknown column 's.id' in 'where clause'
The subselect doesnt know about the results of the main query, is there a solution to bypass this?
Could someone give me a hint to get this working?
Thanks in advance.
Using your subquery in the JOIN you can eliminate the WHERE clause and achieve nearly the same result. Here is your modified query. Hope this solves your problem.
SELECT `s`.`id` AS `seminar_id`, (SUM( `sub`.`seminar_rate` ) / COUNT( `sub`.`seminar_id` )) AS `total_rate`
FROM `seminar` s
INNER JOIN
(
SELECT (SUM( value ) / COUNT( * )) AS `seminar_rate` , `r`.`seminar_id`
FROM `rating` r
INNER JOIN `rating_item` ri ON `r`.`id` = `ri`.`rating_id`
/*WHERE `r`.`seminar_id` = `s`.`id` <- Here is my problem, this is inacessible */
GROUP BY `r`.`seminar_id`
) AS sub ON s.id = sub.`seminar_id`
INNER JOIN `date` d
ON `s`.`id` = `d`.`seminar_id`
INNER JOIN `date_unit` du
ON `d`.`id` = `du`.`date_id`
LEFT JOIN `seminar_subject` su
ON `s`.`id` = `su`.`seminar_id`
LEFT JOIN `subject` suj
ON `su`.`subject_id` = `suj`.`id`
INNER JOIN `user` u
ON `s`.`user_id` = `u`.`id`
INNER JOIN `company` c
ON `u`.`company_id` = `c`.`id`
GROUP BY `du`.`date_id`, `sub`.`seminar_id`

MySQL Invalid Use of Group Function

I'm getting Error Code: 1111. Invalid use of group function when trying to build a query in MySQL. Apparently MySQL doesn't support WITH, which is what I'm more comfortable using.
SELECT DISTINCT `UserID`
FROM `user`
INNER JOIN `message`
ON `user`.`Message` = `message`.`Recipient`
WHERE MAX(`TotalSize`) IN (
SELECT SUM(`message`.`Size`) as `TotalSize`
FROM `message`
INNER JOIN `category`
ON `message`.`CatID` = `category`.`CatID`
WHERE `category`.`CatName` = 'Inbox'
GROUP BY `Recipient`);
SELECT `UserID`, MAX(SUM(message.Size)) as TotalSize
FROM `user`
INNER JOIN `message`
ON `user`.`Message` = `message`.`Recipient`
INNER JOIN category
ON message.CatID = category.CatID
WHERE category.CatName = 'Inbox'
GROUP BY UserID
You need to use HAVING clause instead of WHERE MAX(TotalSize)
SELECT DISTINCT `UserID`
FROM `user`
INNER JOIN `message`
ON `user`.`Message` = `message`.`Recipient`
GROUP BY `UserID`
HAVING MAX(`message`.`Size`) IN (
SELECT SUM(`message`.`Size`) as `TotalSize`
FROM `message`
INNER JOIN `category`
ON `message`.`CatID` = `category`.`CatID`
WHERE `category`.`CatName` = 'Inbox'
GROUP BY `Recipient`);
Group functions are not accessible in WHERE clause , HAVING can filter on aggregates.

MySQL Unknown column in having clause

I'm trying to get all the wins per team, however, SQL decides to throw an error
The following query is being executed:
SELECT `t`.`teamcode`, COUNT(*) AS `gewonnen`
FROM `Team` `t`
INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode`
GROUP BY `w`.`teamthuis`
HAVING `w`.`scorethuis` > `w`.`scoreuit`
#1054 - Unknown column 'w.scorethuis' in 'having clause'
Without aliases:
SELECT `Team`.`teamcode`, COUNT(*) AS `gewonnen`
FROM `Team`
INNER JOIN `Wedstrijd` ON `Wedstrijd`.`teamthuis` = `Team`.`teamcode`
GROUP BY `Wedstrijd`.`teamthuis`
HAVING `Wedstrijd`.`scorethuis` > `Wedstrijd`.`scoreuit`
#1054 - Unknown column 'Wedstrijd.scorethuis' in 'having clause'
There is no need to use HAVING. Try WHERE instead:
SELECT `t`.`teamcode`, COUNT(*) AS `gewonnen`
FROM `Team` `t`
INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode`
WHERE `w`.`scorethuis` > `w`.`scoreuit`
GROUP BY `w`.`teamthuis`
I think if you had select w.scorethuis w.scoreuit both in select statement then 'Having;' would work. But I faced the same problem and I resolved it by the above way.
SELECT `t`.`teamcode`, COUNT(*),***`w`.`scorethuis`, `w`.`scoreuit`*** AS `gewonnen`
FROM `Team` `t`
INNER JOIN `Wedstrijd` `w` ON `w`.`teamthuis` = `t`.`teamcode`
GROUP BY `w`.`teamthuis`
HAVING `w`.`scorethuis` > `w`.`scoreuit`

Store the results of a sub-query for use in multiple joins

I have the following MySQL query, which produces the result I want:
SELECT
`l`.`status`,
`l`.`acquired_by`, `a`.`name` AS 'acquired_by_name',
`l`.`researcher`, `r`.`name` AS 'researcher_name',
`l`.`surveyor`, `s`.`name` AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
But as you can see, it has the same sub-query in it three times. Is there any way to execute this query once and store the result, so I can LEFT JOIN with the cached results instead of executing the same query three times?
I have tried storing it in a variable:
SET #usercache = (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
)
...but this gives me an error:
1241 - Operand should contain 1 column(s)
...and some Googling on this error has left me none the wiser.
Does anyone know how I can make this query more efficient? Or am I just worrying about something that doesn't matter anyway?
I am using PHP/MySQLi if it makes any difference.
Do you really need the subqueries? How about this:
SELECT
`l`.`status`,
`l`.`acquired_by`, COALESCE(`a`.`name`, 'Unassigned') AS 'acquired_by_name',
`l`.`researcher`, COALESCE(`r`.`name`, 'Unassigned') AS 'researcher_name',
`l`.`surveyor`, COALESCE(`s`.`name`, 'Unassigned') AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN `web_users` `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN `web_users` `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN `web_users` `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
you cannot run it once - you are actually using it three times to get three different results...

How to use Having without Selecting field in mysql

Im using this query:
SELECT `projects`.*,
(SELECT SUM(`amount`)
FROM `accountprojectspayment`
WHERE `projects_id` = `projects`.`id`) AS `payed`
FROM `projects`
INNER JOIN `bids` ON `bids`.`id` = `projects`.`bids_id`
HAVING `bids`.`amount` >= `payed`
i get this error: Unknown column 'bids.amount' in 'having clause
But if i change the code to this:
SELECT `projects`.*, `bids`.`amount`,
(SELECT SUM(`amount`)
FROM `accountprojectspayment`
WHERE `projects_id` = `projects`.`id`) AS `payed`
FROM `projects`
INNER JOIN `bids` ON `bids`.`id` = `projects`.`bids_id`
HAVING `bids`.`amount` >= `payed`
the problem get solved but i do not want to use Select bids.amount
Use a derived table e.g. something like this:
SELECT `DT1`.*
FROM (SELECT `projects`.*,
(SELECT SUM(`amount`)
FROM `accountprojectspayment`
WHERE `projects_id` = `projects`.`id`) AS `payed`
FROM `projects`) AS `DT1`
INNER JOIN `bids` ON `bids`.`id` = `DT1`.`bids_id`
WHERE `bids`.`amount` >= `DT1`.`payed`;