dsoy71058 2018-02-24 00:54
浏览 327
已采纳

获取结果列表,并在一个查询中获得总数

I have logic that is meant for pagination, and it works perfectly fine as is. This question is meant for optimization/improvement in regards to how I'm doing something.

I am running two queries to get a result set. The first query gets all items by limit and offset, the second query gets the total count. I need this total to do math for pagination links in the presentation layer.

I want to avoid running two queries, and combine them into one if possible.

For example, if there is 100 items in the database and I run the query below with the LimitStartIndex at 1 and LimitStopIndex at 20, then the query should return 20 results and a count of 100. I currently achieve this in two separate queries just fine, but again I want to do it in one query.

Here is my current setup (using Golang):

var items []*Item
err := r.db.Select(&items, `
    SELECT item.*
    FROM item
    JOIN user
        ON user.username = ?
    JOIN user_item
        ON user_item.item_id = item.id
        AND user_item.user_id = user.id
    ORDER BY item.id DESC
    LIMIT ?,?
`, username, pagination.LimitStartIndex, pagination.LimitStopIndex)
if err != nil {
    // ...
}

var total int
err = r.db.Get(&total, `
    SELECT COUNT(*)
    FROM item
    JOIN user
        ON user.username = ?
    JOIN user_item
        ON user_item.item_id = item.id
        AND user_item.user_id = user.id
`, username)
if err != nil {
    // ...
}

result := &domain.PaginationResult{
    Items: items,
    Total: total,
}

I tried something like this:

SELECT item.*, COUNT(DISTINCT item.id) AS _count
FROM item
JOIN user
    ON user.username = ?
JOIN user_item
    ON user_item.item_id = item.id
    AND user_item.user_id = user.id
ORDER BY item.id DESC
LIMIT ?,?

However I receive this error:

Error 1140: In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'mytable.item.id'; this is incompatible with sql_mode=only_full_group_by

  • 写回答

1条回答 默认 最新

  • dongwen5351 2018-02-24 01:22
    关注

    Ensure to add 'group by' in the query. Hope this helps. Thanks.

    SELECT item.*, COUNT(*) AS _count
    FROM item
    JOIN user
        ON user.username = ?
    JOIN user_item
        ON user_item.item_id = item.id
        AND user_item.user_id = user.id
    GROUP BY item.id        
    ORDER BY item.id DESC
    LIMIT ?, ?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退