douzhenzu0247 2014-07-24 12:08
浏览 24
已采纳

计算数据库中的记录总数,但仅返回X记录

We are shifiting one of our applications from PostGreSQL to MySQL. We have the following query in PostGres -

SELECT 
      idrte
    , left_name
    , gacodemun
    , clsrte
    , speed
    , speed_override
    , ST_AsGeoJSON(geometry) AS geometry
    , count(idrte) OVER() AS total 
FROM 
    aq_routes 
WHERE 
    ST_CONTAINS(
        GeomFromText(
            'Polygon(($geom))'
        ),geometry) 
GROUP BY 
      idrte
    , left_name
    , gacodemun
    , clsrte
    , speed
    , speed_override
    , geometry 
ORDER BY left_name 
LIMIT 150;

We are trying to port this query to MySQL ad have come up with this -

SELECT 
     id AS id
   , left_name AS left_name
   , left_locality AS left_locality
   , class AS class
   , speed AS speed
   , speed_override AS speed_override
   , AsWKB(Geom) AS geom
   , count(id) AS total 
FROM road_segments 
WHERE 
   CONTAINS(
       GeomFromText(
           'Polygon(($geom))'
       ),geom) 
GROUP BY 
      id
    , left_name
    , class
    , speed
    , speed_override
    , geom 
ORDER BY left_name 
LIMIT 150;

There are some field changes, but on the whole the intended functionality is to be the same.

You'll notice the call the OVER() in the PostGreSQL. The table we are querying has a lot of data. So to the user, we display only 150 records but tell him the count of all the records. With PostGres this was possible through a single call but we don't have OVER() function in MySQL.

What other alternatives do we have other than querying the database a second time. A second query to the database is increasing the response time by at least 15 seconds and sometimes even timing out.

  • 写回答

1条回答 默认 最新

  • duanmian1085 2014-07-24 12:21
    关注

    I think you want to use FOUND_ROWS() and CALC_FOUND_ROWS(). You can review the documentation here.

    The basic idea is:

    select CALC_FOUND_ROWS id, . . .
    . . .
    

    Then use the function FOUND_ROWS() to return the value to the application.

    Unfortunately, to get this value as a column value, I think you would need to run the query twice, essentially:

    select . . ., x.cnt
    from . . . cross join
         (select count(*) as cnt from <your query here>) x
    . . .
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误