在子查询的子查询中使用父查询的列

时间:2016-05-11 14:59:41

标签: mysql sql variables

使用此查询:

SELECT
    `id`,
    `type`,
    `subtype`,
    `title`,
    `shortdesc`,
    (SELECT COUNT(*)
     FROM `story_comments`
     WHERE `parent_id` = t1.`id`) as comments,
    (SELECT
        (ROUND( (
            SELECT (SUM(`rating` * `count`) / SUM(`count`) ) ) * 2) ) / 2 as result
            FROM
                    (SELECT rating, COUNT(*) as count
                     FROM `story_ratings` WHERE `parent_id` = t1.`id`
                     GROUP BY rating) as val) as rating,
    `calls`,
    `user`
FROM
    `storys` t1
WHERE
    `open` = 1 AND
    `modremove` = 0 AND
    `modblock` = ''
ORDER BY
    `opening`
DESC LIMIT 16;

我收到此错误:#1054 - 未知栏' t1.id' in' where子句',这是由子查询中的子查询(FROM之后的子查询)引起的。

但是第一个子查询中的t1.id工作正常。为什么我不能在FROM-subquery中使用它?我也试过变量,这也没有用:

SELECT @i := `id` id, `type`, `subtype`, `title`, `shortdesc`, (SELECT COUNT(*) FROM `story_comments` WHERE `parent_id` = t1.`id`) as comments, 

(SELECT (ROUND( (SELECT (SUM(`rating` * `count`) / SUM(`count`) ) ) * 2) ) / 2 as result FROM (SELECT rating, COUNT(*) as count FROM `story_ratings` WHERE `parent_id` = @i GROUP BY rating) as val) as rating,

`calls`, `user` FROM `storys` t1 WHERE `open` = 1 AND `modremove` = 0 AND `modblock` = '' ORDER BY `opening` DESC LIMIT 16;

使用@i变量,结果在每一行都返回NULL,这是错误的。

1 个答案:

答案 0 :(得分:0)

哇。这么多嵌套子查询。不要将查询嵌套到地球的末端,而是使用JOIN并聚合数据来计算您需要的数据。我不得不对你的表格结构做一些猜测,因为你没有提供它们(在发布数据库问题时你应该总是这样做。)

SELECT
    S.id,
    S.type,
    S.subtype,
    S.title,
    S.shortdesc,
    COUNT(DISTINCT SC.id) AS comments,
    AVG(SR.rating) AS rating,
    calls,
    user
FROM
    Storys S  -- Storys isn't the plural of Story, BTW
LEFT OUTER JOIN Story_Comments SC ON SC.parent_id = S.id
LEFT OUTER JOIN Story_Ratings SR ON SR.parent_id = S.id
WHERE
    S.open = 1 AND
    S.modremove = 0 AND
    S.modblock = ''
GROUP BY
    S.id,
    S.type,
    S.subtype,
    S.title,
    S.shortdesc,
    S.calls,
    S.user
ORDER BY
    opening
DESC LIMIT 16;

我不认为“* 2 ... / 2”根据各种括号执行您认为的操作,并且根据您{{1}的数据类型,舍入可能不在此处}列(再次,没有表结构,所以我猜不到)。

我没有方便的MySQL服务器,但在SQL Server上测试此代码(调整rating函数的差异)给出了与第一次查询相同的结果。