perf(query): 优化后台手机号精确查询

This commit is contained in:
yml2213
2026-11-02 18:28:12 +08:00
parent 9c379b7e0c
commit 599e22331d
17 changed files with 254 additions and 62 deletions
+13 -7
View File
@@ -134,11 +134,9 @@ func (r *Repository) adminDisputeCountQuery(ctx context.Context, query AdminList
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
Joins("JOIN rental_listings AS l ON l.id = o.listing_id")
}
if len(kw) == 11 && kw[0] == '1' && isAllDigits(kw) {
if isPhoneKeyword(kw) {
return r.db.WithContext(ctx).Table("disputes AS d").
Joins("JOIN rental_orders AS o ON o.id = d.order_id").
Joins("JOIN users AS owner ON owner.id = o.owner_id").
Joins("JOIN users AS renter ON renter.id = o.renter_id")
Joins("JOIN rental_orders AS o ON o.id = d.order_id")
}
return r.adminFilterQuery(ctx)
}
@@ -152,9 +150,13 @@ func applyAdminListFilters(db *gorm.DB, query AdminListQuery) *gorm.DB {
}
if keyword := strings.TrimSpace(query.Keyword); keyword != "" {
upper := strings.ToUpper(keyword)
if len(keyword) == 11 && keyword[0] == '1' && isAllDigits(keyword) {
// 11 位手机号:命中 users(phone) 唯一索引
db = db.Where("(owner.phone = ? OR renter.phone = ?)", keyword, keyword)
if isPhoneKeyword(keyword) {
// 先由 users(phone) 唯一索引解析用户,再走订单号主/租客索引。
db = db.Where(
"(o.owner_id = (SELECT id FROM users WHERE phone = ?) OR o.renter_id = (SELECT id FROM users WHERE phone = ?))",
keyword,
keyword,
)
} else if strings.HasPrefix(upper, "RO") || strings.HasPrefix(upper, "ORD") {
// 订单号:命中 rental_orders(order_no) 唯一索引
db = db.Where("o.order_no = ?", keyword)
@@ -190,3 +192,7 @@ func isAllDigits(s string) bool {
}
return true
}
func isPhoneKeyword(s string) bool {
return len(s) == 11 && s[0] == '1' && isAllDigits(s)
}
@@ -770,9 +770,9 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
wantSQLFrag string
}{
{
name: "11位手机号路由至users(phone)",
name: "11位手机号先解析用户再走订单角色索引",
query: AdminListQuery{Keyword: "13800138000"},
wantSQLFrag: "owner.phone = ? OR renter.phone = ?",
wantSQLFrag: "o.owner_id = (SELECT id FROM users WHERE phone = ?)",
},
{
name: "RO前缀订单号路由至rental_orders(order_no)",