From ffabf3d396b500d69fd33017d564eb1a3b077aeb Mon Sep 17 00:00:00 2001 From: Sakurasan <26715255+Sakurasan@users.noreply.github.com> Date: Mon, 10 Aug 2026 20:17:39 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20/history=20=E6=B6=88=E9=99=A4=E9=A2=98?= =?UTF-8?q?=E6=9D=90=E6=9F=A5=E8=AF=A2=20N+1=20=E5=B9=B6=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- backend/routes/core_stocks.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/backend/routes/core_stocks.py b/backend/routes/core_stocks.py index de6a6fc..e7e01d8 100644 --- a/backend/routes/core_stocks.py +++ b/backend/routes/core_stocks.py @@ -52,7 +52,7 @@ async def active_core_stocks(): s["lastAppear"] = r["trade_date"] stocks = list(stock_days.values()) - # 稳定排序:先按最近上榜日降序,再按出现次数降序 + # 稳定排序:先按出现次数降序,再按最近上榜日降序 stocks.sort(key=lambda x: x.get("lastAppear") or "", reverse=True) stocks.sort(key=lambda x: -x["appearCount"]) return JSONResponse({"dates": dates, "stocks": stocks}, headers=_NO_CACHE_HEADERS) @@ -67,14 +67,20 @@ async def core_stock_history(date: str = Query(..., description="交易日 YYYY- rows = conn.execute( "SELECT * FROM daily_core_stocks WHERE trade_date = ? ORDER BY rank ASC", (date,) ).fetchall() + # 一次性取该日全部题材关联,按 stock_code 分组,避免逐股 N+1 查询 + themes_rows = conn.execute( + "SELECT stock_code, theme_code, theme_name FROM daily_core_stock_themes WHERE trade_date = ?", + (date,), + ).fetchall() + themes_by_stock: dict[str, list] = {} + for t in themes_rows: + themes_by_stock.setdefault(t["stock_code"], []).append( + {"theme_code": t["theme_code"], "theme_name": t["theme_name"]} + ) items = [] for r in rows: d = dict_from_row(r) - themes = conn.execute( - "SELECT theme_code, theme_name FROM daily_core_stock_themes WHERE trade_date = ? AND stock_code = ?", - (date, d["stock_code"]), - ).fetchall() - d["themes"] = [dict(t) for t in themes] + d["themes"] = themes_by_stock.get(d["stock_code"], []) items.append(d) return JSONResponse({"date": date, "items": items}, headers=_NO_CACHE_HEADERS) finally: