0

I have this query and I want to get the row count, but I also get MySql error: ERROR 1248 (42000): Every derived table must have its own alias

SELECT SUM(total) FROM
                (
                    SELECT COUNT(1) AS total FROM toys tiw 
                    LEFT JOIN item ti 
                    ON tiw.item_id = ti.id 
                    WHERE tiw.user_id='1785335'
                )
                UNION

                (

                    SELECT COUNT(1) as total 
                    FROM gadgets tfiw 
                    LEFT JOIN flair_store tfs 
                    ON tfiw.flair_id = tfs.id 
                    WHERE tfiw.user_id='1785335'
                ) t1
4

1 回答 1

3

如果您希望获得sum()两个总数,我相信您想使用:

SELECT SUM(total) 
FROM
(
    SELECT COUNT(1) AS total 
    FROM toys tiw 
    LEFT JOIN item ti 
        ON tiw.item_id = ti.id 
    WHERE tiw.user_id='1785335'
    UNION ALL
    SELECT COUNT(1) as total 
    FROM gadgets tfiw 
    LEFT JOIN flair_store tfs 
        ON tfiw.flair_id = tfs.id 
    WHERE tfiw.user_id='1785335'
) d

注意我也会使用UNION ALL. UNION ALL即使两个查询中的总计数相同,也会返回两个值。将UNION删除重复项。

就您的错误而言,您的子查询之一缺少别名。

于 2013-11-13T17:28:44.883 回答