MySQL“每个派生表必须有自己的别名”

时间:2013-09-11 09:12:51

标签: mysql sql

我对这种奇怪的MySQL行为感到有些困惑。我收到了可怕的Every derived table must have its own alias错误。

通常,我可以通过在主AS语句中添加SELECT子句来避免这种情况,但是它看起来不适用于以下示例:

SELECT SUM (`a`.`total`) AS `total` FROM (
    SELECT COUNT(DISTINCT(`item_sales`.`id`)) AS `total`,
    (SELECT COUNT(DISTINCT(`sale_item`)) AS `offers` FROM `item_sales_bids` WHERE `user_id` = 2) AS `offers`
        FROM `item_sales`
        INNER JOIN `item_sales_bids` ON `item_sales`.`id` = `item_sales_bids`.`sale_item`
        WHERE `item_sales`.`buyer` != 2
            AND `item_sales`.`sold` = 1
        GROUP BY `item_sales`.`id`
        HAVING `offers` > 0
    ) UNION (
        SELECT COUNT(*) AS `total`,
            `item_sales`.`reserve`,
            (SELECT COUNT(*) FROM `item_sales_bids` WHERE `user_id` = 2) AS `bids`,
            (SELECT MAX(`max_bid`) AS `max` FROM `item_sales_bids` WHERE `user_id` = 2) AS `maxBid`,
            SUM((`item_sales`.`list_date` + (`item_sales`.duration * 86400)) - UNIX_TIMESTAMP()) AS `endTime`
            FROM `item_sales`
            INNER JOIN `item_sales_bids` ON `item_sales_bids`.`sale_item` = `item_sales`.`id`
            GROUP BY `item_sales`.`id`
            HAVING `endTime` < 0
                AND `maxBid` < `item_sales`.`reserve`
    )
) `a`

有谁可以指出我错过了什么?请注意,为连接添加别名会导致相同的错误。

2 个答案:

答案 0 :(得分:4)

您应该在子查询中放置UNION关键字,如下所示

SELECT SUM (`a`.`total`) AS `total` 
FROM (
    SELECT COUNT(DISTINCT(`item_sales`.`id`)) AS `total`,
    (SELECT COUNT(DISTINCT(`sale_item`)) AS `offers` FROM `item_sales_bids` WHERE `user_id` = 2) AS `offers`
    FROM `item_sales`
    INNER JOIN `item_sales_bids` ON `item_sales`.`id` = `item_sales_bids`.`sale_item`
    WHERE `item_sales`.`buyer` != 2
        AND `item_sales`.`sold` = 1
    GROUP BY `item_sales`.`id`
    HAVING `offers` > 0

UNION 

SELECT COUNT(*) AS `total`,
    `item_sales`.`reserve`,
    (SELECT COUNT(*) FROM `item_sales_bids` WHERE `user_id` = 2) AS `bids`,
    (SELECT MAX(`max_bid`) AS `max` FROM `item_sales_bids` WHERE `user_id` = 2) AS `maxBid`,
    SUM((`item_sales`.`list_date` + (`item_sales`.duration * 86400)) - UNIX_TIMESTAMP()) AS `endTime`
    FROM `item_sales`
    INNER JOIN `item_sales_bids` ON `item_sales_bids`.`sale_item` = `item_sales`.`id`
    GROUP BY `item_sales`.`id`
    HAVING `endTime` < 0
        AND `maxBid` < `item_sales`.`reserve`
) `a`

答案 1 :(得分:1)

您可以在子查询中包含UNION

SELECT SUM (`a`.`total`) AS `total`
FROM
(
    --- your first query
    UNION
    --- your second query
) a