簡體   English   中英

如何改善分頁的SQL查詢?

[英]How to improve SQL query for pagination?

我正在使用數據庫和servlet,出現了這樣的問題。 我需要從數據庫中接收每頁6條的數據,為此,我提出了這樣的要求

SELECT *, COUNT(*) AS 'count' 
FROM product
INNER JOIN product_category
  on product.product_category_id = product_category.id 
INNER JOIN  company_manufacturer_product 
  on product.company_manufacturer_product_id =
     company_manufacturer_product.id
GROUP BY 1 LIMIT 6 OFFSET 0;

其中6是每頁的最大項目數,0是頁數乘以最大商品數量。 但是通過第二頁上的這種實現,我有重復的產品我該如何改進它?

我形成請求的代碼部分:

StringBuilder startResponse = new StringBuilder("SELECT *, COUNT(*) AS 'count' FROM product " +
                "INNER JOIN product_category on product.product_category_id = product_category.id " +
                "INNER JOIN company_manufacturer_product on product.company_manufacturer_product_id=company_manufacturer_product.id");
if (nonNull(form.getProductMax()) && nonNull(form.getPage())) {
            startResponse.append(" LIMIT ").append(form.getProductMax()).append(" OFFSET ").append(form.getPage() * form.getProductMax());
        }

我的數據庫在沒有LIMIT和OFFSET的情況下響應:

在此處輸入圖片說明

當我使用上述查詢時,我的數據庫將響應,當我轉到商品的第一頁時,此請求將發送到數據庫: 在此處輸入圖片說明

當我轉到商品的第二頁時,我將這樣的請求發送到數據庫

SELECT * , COUNT(*) AS 'count' 
FROM product 
INNER JOIN product_category
  on product.product_category_id = product_category.id
INNER JOIN company_manufacturer_product 
  on product.company_manufacturer_product_id = 
     company_manufacturer_product.id
GROUP BY 1 LIMIT 6 OFFSET 6;

我有這樣的回應:

在此處輸入圖片說明

我不明白是什么問題。 我必須使用COUNT個請求! 如何證明呢?

不反對這個問題的解決方案,根據上述方法,對原始sql添加order by即可解決問題。 但是我認為我有更好的分頁習慣:使用has_morelast_product_idlimit_num類的參數將客戶端與服務器連接。

has_more指示服務器中是否剩余數據; last_product_id表示最后響應數據的id; limit_num表示每頁的數量。

因此,客戶端可以使用has_more來確定是否發送請求,如果是,則客戶端向服務器發送帶有last_product_idlimit_num的請求; 對於服務器,sql可以是這樣的:

select * from table where id < $last_product_id order by id desc
limit $limit_num + 1; =>$datas

並且,count($ datas)和$ limit_num可以計算has_morelast_product_id的值:

$has_more = 0;
$data_num = count($datas);
if ($data_num > $page_limit) {
    $has_more = 1;
    array_pop($datas);
    $data_num--;
}

$last_product_id = end($datas)['id'] ?? 0; 

SELECT *,COUNT(product.id)作為'count',來自產品INNER JOIN在product.product_category_id上的product_category = product_category.id INNER JOIN company_manufacturer_product在product.company_manufacturer_product_id = company_manufacturer_product.id上按product.id分組按product.id進行訂購SET LIMIT 6 OFF 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM