mysql – How to pass main query value into a join in subquery
I have the following query (well… the part that bugs me of it):
SELECT DISTINCT `serv`.`id`, `serv`.`name`, `prj`.`id` AS `idProject`, `prj`.`name` AS `projectName`, `units`.`id` AS `idUnit`,
`units`.`name` AS `unitName`, `units`.`description` AS `unitDescription`, `units`.`descriptionLong` AS `unitLongDescription`,
`units`.`address`, `units`.`telephone`, (
SELECT DISTINCT GROUP_CONCAT(CONCAT(`subserv`.`id`, '|', `subserv`.`name`, '|', `links`.`continuous`))
FROM `" . DBT_SERV . "` AS `subserv`
JOIN `" . DBT_SERV_LINKS . "` AS `links` ON (
`links`.`deleted` = 0 AND
`links`.`idProject` = `serv`.`idProject` AND
`links`.`mandatory` = '1' AND
`links`.`subserviceLink` = 1 AND
`links`.`serviceFrom` LIKE CONCAT ('|', `serv`.`id`,'|') AND
`links`.`serviceTo` LIKE CONCAT('|', `subserv`.`id`, '|')
)
WHERE `idParentService` = `serv`.`id`
AND `subserv`.`deleted` = 0
AND `subserv`.`onSaleStatus` = 'onSale'
AND `subserv`.`serviceGroup` = 'SS'
) AS `subservices`, (
SELECT `file`
FROM `" . DBT_GALLERY . "` AS `gallery`
WHERE `gallery`.`category` = 'accommodationUnit'
AND `idObject` = `idUnit`
LIMIT 1
) AS `picture`
FROM `" . DBT_SERV . "` AS `serv`
ETC., ETC… some more joins and a where.
My problem is that I get the following error: #1054 – Unknown column ‘serv.idProject’ in ‘on clause’
If I remove links
.idProject
= serv
.idProject
AND I get #1054 – Unknown column ‘serv.id=’ in ‘on clause’.
Basically… I can’t see anything from serv
inside the ON clause. If I remove whole JOIN query works, so in the WHERE clause serv
is visible. Any idea how I can make it work in the ON clause also?
Try this
SELECT DISTINCT `serv`.`SID`, `serv`.`SNAME`, `serv`.`SIDP`, `prj`.`id` AS `idProject`,
`prj`.`name` AS `projectName`, `units`.`id` AS `idUnit`,
`units`.`name` AS `unitName`, `units`.`description` AS `unitDescription`,
`units`.`descriptionLong` AS `unitLongDescription`, `units`.`address`,
`units`.`telephone`,
(
SELECT DISTINCT GROUP_CONCAT(CONCAT(`subserv`.`id`, '|', `subserv`.`name`, '|', `links`.`continuous`))
FROM `" . DBT_SERV . "` AS `subserv`
JOIN `" . DBT_SERV_LINKS . "` AS `links` ON (
`links`.`deleted` = 0 AND
`links`.`idProject` = `serv`.`SIDP` AND
`links`.`mandatory` = '1' AND
`links`.`subserviceLink` = 1 AND
`links`.`serviceFrom` LIKE CONCAT ('|', `serv`.`SID`,'|') AND
`links`.`serviceTo` LIKE CONCAT('|', `subserv`.`id`, '|')
)
WHERE `idParentService` = `serv`.`SID`
AND `subserv`.`deleted` = 0
AND `subserv`.`onSaleStatus` = 'onSale'
AND `subserv`.`serviceGroup` = 'SS'
) AS `subservices`, (
SELECT `file`
FROM `" . DBT_GALLERY . "` AS `gallery`
WHERE `gallery`.`category` = 'accommodationUnit'
AND `idObject` = `idUnit`
LIMIT 1
) AS `picture`
FROM
(SELECT `id` AS `SID`, `idProject` AS `SIDP`, `name` AS `SNAME` FROM `" . DBT_SERV . "`) AS serv
ETC., ETC... some more joins and a where.
SID, SNAME and SIDP alias are defined in the principal query so it should be accesible into subquerys.