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: