【问题标题】:Get total number of rows when using LIMIT and UNION in mysql query在mysql查询中使用LIMIT和UNION时获取总行数
【发布时间】:2014-07-15 17:28:31
【问题描述】:

Query:

SELECT
    tbl_a.id as aid,
    tbl_a.name as aname,
    null location,
    .....
    .....
    from tbl_a
    .........//left join to fetch some other data
    .........//where condition
UNION ALL
    0 aid,
    null aname,
    tbl_b.location as location,
    .....
    .....
    from tbl_b
    .........//left join to fetch some other data
    .........//where condition
limit '.$recordperpage.' OFFSET '.$offset.'

这里,$recordperpage$offset 是动态的。

现在我正在尝试获取所有不。行数没有限制。

例如:
有限制的行数:20
无限制的行数:50
我想取不。没有限制的行数(意味着 50)。

那么如何实现呢? 提前致谢。

【问题讨论】:

  • 真的不明白你的问题如果你想无限制地全部记录那么remove limit clause
  • 问题是我使用分页,所以我必须知道总数是多少。行数?
  • 使用 PHP count($result_array) 获取记录数
  • 不包含。限制内的记录。假设:无限制的总记录数为 50,但使用限制为 20,那么您的方法返回 20,而不是 50。

标签: php mysql


【解决方案1】:

也许 SQL_CALC_FOUND_ROWS 适合您? 看看这里。

How to count all records but only retrieve (LIMIT) a specific number for display?

【讨论】:

    【解决方案2】:

    这个查询可以解决问题:

    SELECT count(*) as count
    FROM
    (SELECT
        tbl_a.id as aid,
        tbl_a.name as aname,
        null location,
        .....
        .....
        from tbl_a
        .........//left join to fetch some other data
        .........//where condition
    UNION ALL
        0 aid,
        null aname,
        tbl_b.location as location,
        .....
        .....
        from tbl_b
        .........//left join to fetch some other data
        .........//where condition
    ) union_table
    

    【讨论】:

      猜你喜欢
      • 2015-12-10
      • 2010-11-27
      • 2015-05-07
      • 1970-01-01
      • 2011-08-21
      • 2014-05-08
      • 2012-10-04
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多