You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于MySQL中Retrosheet棒球数据的日期与序列字段SQL查询需求

Extract Date and Game Sequence from Retrosheet GAME_ID in MySQL

Got it, since you've already imported your Retrosheet data into MySQL and need to pull out the date and game sequence from that GAME_ID field for frequent queries, here are a couple of practical solutions tailored to your needs:

1. Temporary Extraction (For One-Off Queries)

If you just need these values for a single query or ad-hoc analysis, use string functions to slice and convert the GAME_ID on the fly:

SELECT
  GAME_ID,
  -- Extract and convert the 8-digit date segment to a DATE type
  STR_TO_DATE(SUBSTRING(GAME_ID, 4, 8), '%Y%m%d') AS game_date,
  -- Pull the final character as an unsigned integer for sequence sorting
  CAST(RIGHT(GAME_ID, 1) AS UNSIGNED) AS game_sequence
FROM your_table_name;

Breakdown:

  • SUBSTRING(GAME_ID, 4, 8) grabs the 8 characters starting at position 4 (skipping the 3-letter home team code)
  • STR_TO_DATE(..., '%Y%m%d') converts that numeric string into a proper MySQL DATE value, which works seamlessly with date functions like YEAR() or range queries
  • RIGHT(GAME_ID, 1) fetches the final character, and CAST(AS UNSIGNED) turns it into an integer for easier sorting or filtering (e.g., WHERE game_sequence = 1 for the second game of a doubleheader)

Since you mentioned most queries will use these fields, adding stored generated columns to your table will save you from repeating string manipulation every time. MySQL will automatically maintain these columns whenever GAME_ID is updated:

-- Add the date column (stored physically for fast access)
ALTER TABLE your_table_name
ADD COLUMN game_date DATE AS (STR_TO_DATE(SUBSTRING(GAME_ID, 4, 8), '%Y%m%d')) STORED;

-- Add the sequence column
ALTER TABLE your_table_name
ADD COLUMN game_sequence INT AS (CAST(RIGHT(GAME_ID, 1) AS UNSIGNED)) STORED;

Once added, you can use these columns just like any other table column:

-- Example: Get all second doubleheader games from 1992
SELECT *
FROM your_table_name
WHERE game_date BETWEEN '1992-01-01' AND '1992-12-31'
  AND game_sequence = 1; -- Note: Retrosheet uses 0 for the first game, 1 for the second, 2 for a third game

Quick Checks to Avoid Issues:

Before implementing, verify your GAME_ID values all follow the expected 12-character format:

-- Find malformed GAME_IDs that might break conversions
SELECT GAME_ID
FROM your_table_name
WHERE LENGTH(GAME_ID) != 12;

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:50:33