如何解决这个特定的查询?

时间:2011-05-20 13:51:47

标签: mysql

SELECT    id,  count(*) as Number
FROM     (SELECT id  FROM t1
            UNION ALL
          SELECT id  FROM t2
            UNION ALL
          SELECT id  FROM t3
         ) t
GROUP BY  id
ORDER BY  Number DESC

这是给我正确结果的查询。但是当我想添加调用它会引发错误时。

SELECT    id, count(*) as Number
FROM     (SELECT id from t1
            UNION ALL
          select id from t2
            UNION ALL
          select id from t3
         ) t
WHERE     Number > 10 
GROUP BY  id
ORDER BY  Number DESC

2 个答案:

答案 0 :(得分:2)

您希望使用HAVING子句而不是WHERE来测试聚合函数的条件。

select id, count(*) as Number 
    from (select id 
              from t1 
          UNION ALL 
          select id 
              from t2 
          UNION ALL 
          select id 
              from t3) t 
    group by id
    having Number > 10
    order by Number desc;

答案 1 :(得分:0)

select
    id,
    count(*) as Number
from
    (
    select
        id
    from
        t1
    UNION ALL
        select
            id
        from
            t2
        UNION ALL
            select
                id
            from
                t3
    )t
group by
    id
HAVING
    Number > 10
order by
    Number desc;

尝试一下 - 如果您的查询易于阅读,我认为它更容易调试...