如何使用别名显示两个计数之间的差异?

时间:2014-08-30 17:36:37

标签: mysql sql

我正在创建自定义视图,以显示数据库中不同内容的总计,并且我还希望显示差异。

例如;

SELECT
   (SELECT COUNT(*) FROM `documents`) AS `doc_count`,
   (SELECT COUNT(*) FROM `contacts`) AS `user_count`,
   (`doc_count` - `user_count`) AS `difference`;

我以这种方式使用别名时出错。有没有办法在不重复select count(*)查询的情况下编写此查询。

4 个答案:

答案 0 :(得分:2)

您可以使用其他查询包装两个查询:

SELECT doc_count, user_count, doc_count - user_count AS difference
FROM   ((SELECT COUNT(*) FROM `documents`) AS doc_count,
        (SELECT COUNT(*) FROM `contacts`) AS user_count) t

答案 1 :(得分:1)

不能在同一级别的查询中使用别名,您必须使用整个表达式或使用子选择

SELECT
   (SELECT COUNT(*) FROM `documents`) AS `doc_count`,
   (SELECT COUNT(*) FROM `contacts`) AS `user_count`,
   ((SELECT COUNT(*) FROM `documents`) - (SELECT COUNT(*) FROM `contacts`)) AS `difference`;

答案 2 :(得分:1)

这是一个“解决方法”,可以获得您正在寻找的结果:

SELECT C.doc_count
    ,C.user_count
    ,C.doc_count - C.user_count AS `difference`
FROM (SELECT
         (SELECT COUNT(*) FROM `documents`) AS `doc_count`
         ,(SELECT COUNT(*) FROM `contacts`) AS `user_count`) C

但我不确定这种查询的表现......

希望这会对你有所帮助

答案 3 :(得分:1)

我会将这些内容移到from子句并使用cross join

SELECT d.doc_count, u.user_count, (d.doc_count - u.user_count) as difference
FROM (SELECT COUNT(*) as doc_count FROM `documents`) d CROSS JOIN
     (SELECT COUNT(*) as user_count FROM `contacts`) u;