MySQL Query,(从子查询访问mainquery)

时间:2014-03-28 11:34:17

标签: mysql join subquery

我有一个问题,我需要在子查询中依赖主查询结果的WHERE子句,否则我的结果会出错并且查询需要太长时间/不可执行。

我需要此查询来创建搜索服务器所需的视图的情况支持我无法将其拆分为两个查询的问题,也无法动态处理脚本。

以下查询出现问题:

    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`

此查询应计算每个研讨会的评分总费率。 但是我的评分存储在我的&#34;评级&#34;表格,应该现场处理。

(旁注:如果你想知道所有的连接:这个查询有更多的SELECT&#ed;字段,我只是删除它们,因为它们不是解决问题的必要条件,并且使查询看起来不那么复杂[我知道它仍然是&gt;。&gt;] ...)

原因是我希望以后我的搜索引擎可以对这些结果进行排序 在用户排序参数上,为什么我在这个查询中需要它。

问题本身非常明显: ERROR 1054(42S22):未知列&#39; s.id&#39;在&#39; where子句&#39;

subselect不知道主查询的结果,是否有解决方案绕过这个?

有人可以给我一个暗示让这个工作吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

JOIN中使用子查询可以消除WHERE子句并获得几乎相同的结果。这是您修改过的查询。希望这能解决你的问题。

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`