我最近遇到了这个问题。问题是要解决两个部分。首先我必须在我的 FROM 子句中使用一个内部选择,它只在主键上为我做限制和偏移:
$subQuery = DB::raw("( SELECT id FROM titles WHERE id BETWEEN {$startId} AND {$endId} ORDER BY title ) as t");
然后我可以将其用作查询的 from 部分:
'titles.id',
'title_eisbns_concat.eisbns_concat',
'titles.pub_symbol',
'titles.title',
'titles.subtitle',
'titles.contributor1',
'titles.publisher',
'titles.epub_date',
'titles.ebook_price',
'publisher_licenses.id as pub_license_id',
'license_types.shortname',
$coversQuery
)
->from($subQuery)
->leftJoin('titles', 't.id', '=', 'titles.id')
->leftJoin('organizations', 'organizations.symbol', '=', 'titles.pub_symbol')
->leftJoin('title_eisbns_concat', 'titles.id', '=', 'title_eisbns_concat.title_id')
->leftJoin('publisher_licenses', 'publisher_licenses.org_id', '=', 'organizations.id')
->leftJoin('license_types', 'license_types.id', '=', 'publisher_licenses.license_type_id')
我第一次创建这个查询时,我在 MySql 中使用了 OFFSET 和 LIMIT。这一直很好,直到我超过第 100 页,然后偏移量开始变得难以忍受。在我的内部查询中将其更改为 BETWEEN 可以加快任何页面的速度。我不知道为什么 MySql 没有加快 OFFSET 的速度,但似乎又把它卷了回来。