【问题标题】:Is it possible to have result and row count of the result in adjacent columns?是否可以在相邻列中获得结果和行数?
【发布时间】:2012-08-31 12:15:33
【问题描述】:

假设我们有一张桌子t1

>desc t1;
      id     int 
     name    varchar(30)

>select count(*) from t1;
      count(*)
       10

是否可以获取结果为

id   name   count
1    abc     10
2    def     10
.     .      .
.     .      .
.     .      .

实际结果列idname 和结果查询的计数count 在同一个结果集中。有可能吗? 基本思想是获取结果行计数以及结果,而不必单独查询数据库以获取计数。即使是子查询也可以。

谢谢。

【问题讨论】:

  • count 是第一个。总结果集的行数,而不仅仅是当前行,因此它必须是常数。

标签: mysql sql jdbc


【解决方案1】:
SELECT * FROM t1, (SELECT COUNT(*) AS count FROM t1) t2

【讨论】:

    【解决方案2】:

    试试:

    select id, name, (select count(*) from t1) as cnt from t1;
    

    【讨论】:

      【解决方案3】:

      是的,这是可能的。由于 MySQL 优化东西的方式,它也非常有效

        SELECT t.*, 
               (select count(*) from t1) as count
          FROM t1 t
      

      【讨论】:

      • @Olloe Jones 是否可以在此查询中返回多个列:(select count(*), SUM(COLUMN1) from t1) as count
      • 是的。这是可能的,但 SUM() 的效率不如 COUNT()。
      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 2021-06-08
      • 2020-08-05
      • 2011-01-27
      • 2022-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多