[英]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_more
, last_product_id
和limit_num
類的參數將客戶端與服務器連接。
has_more
指示服務器中是否剩余數據; last_product_id
表示最后響應數據的id; limit_num
表示每頁的數量。
因此,客戶端可以使用has_more
來確定是否發送請求,如果是,則客戶端向服務器發送帶有last_product_id
和limit_num
的請求; 對於服務器,sql可以是這樣的:
select * from table where id < $last_product_id order by id desc
limit $limit_num + 1; =>$datas
並且,count($ datas)和$ limit_num可以計算has_more
和last_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.