MySQL存储过程列名称连接语法

时间:2014-12-02 17:15:15

标签: mysql stored-procedures

我从这个存储过程中得到各种错误,从未定义的列名到不明确的字段名。

我要做的是选择每个订阅者ID,其中action,share,test,viral和total处于最高值。对于每个最高值,subscriberID可以不同,因此您最多可以返回5个subscriberID。也许我的逻辑不在这里,但下面是我的代码(请注意这仅适用于' action'列):

  SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`

  FROM `subscribers_points` set1

  JOIN
        (
        SELECT `subscriber_id`, MAX(`action`) AS actionMax
        FROM `subscribers_points`
        WHERE `year` = _year
        AND `month` = _month
        GROUP BY `subscriber_id`
        ) groupedAction

  ON set1.subscriber_id=groupedAction.subscriber_id

  WHERE `year` = _year

  AND `month` = _month;

^这导致了'未知列' set1.subscriber_id'在'字段列表'

这对我来说是正确的。我不知道造成错误的原因。

2 个答案:

答案 0 :(得分:0)

在分组动作之前使用'as'。

  SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`

  FROM `subscribers_points` set1

  JOIN
        (
        SELECT `subscriber_id`, MAX(`action`) AS actionMax
        FROM `subscribers_points`
        WHERE `year` = _year
        AND `month` = _month
        GROUP BY `subscriber_id`
        ) as groupedAction

  ON set1.subscriber_id=groupedAction.subscriber_id

  WHERE `year` = _year

  AND `month` = _month;

答案 1 :(得分:0)

试试这个......没有大部分的反击......你只需要反叛来逃避保留的话等等。

SELECT set1.subscriber_id, set1.action, set1.share, set1.test, set1.viral, 
( set1.action + set1.share + set1.test + set1.viral ) AS "total", abuse_flag
FROM subscribers_points set1
JOIN (
    SELECT subscriber_id, MAX(`action`) AS actionMax
    FROM subscribers_points
    WHERE year = _year
    AND month = _month
    GROUP BY subscriber_id
    ) as groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE year = _year
AND month = _month;