# Table Heat Field Count and Query User Count Statistics with TOP Ranking (MySQL)

## Prompt
I need you to generate a MySQL script that retrieves the current day's data from the heat table, counts the number of heat fields queried and the number of querying users per table, and lands the top 10000 rows ranked by heat in descending order.

**Business Background and Objective**: Retrieve the current day's data from the heat table, count how many fields and how many users queried each table, and land the top 10000 rows ranked by heat in descending order into the output table.

**Input Table (full name + brief description)**:
- `internal_platform_db.sql_heat_column_to_ao_mysql_010` (table heat field summary table)

(Please connect to the database and query to confirm the table structure and field semantics.)

**Filter Condition**:
- `imp_date = '20260507'`

**Derived Field Rules**:
- `column_count`: Take the JSON array length of the `column_list` field (i.e., the number of fields), which can be implemented using `JSON_LENGTH(column_list)`; equivalent method: remove brackets and quotes, then split by comma and take the length
- `user_count`: Apply the same treatment to the `user_list` field, taking the JSON array length (i.e., the number of users)

**Sorting and Limit**:
- Sort by `heat DESC, column_count DESC, user_count DESC`
- Take the first 10000 rows

**Output Requirements**:
- Target table: `internal_platform_db.sql_heat_column_to_ao_top_mysql_010`
- Output field order: `imp_date` (VARCHAR), `databasename` (VARCHAR), `tablename` (VARCHAR), `column_list` (VARCHAR), `user_list` (VARCHAR), `heat` (VARCHAR), `column_count` (VARCHAR), `user_count` (VARCHAR)
- No deduplication or aggregation
- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data
- Use standard MySQL syntax; do not use Hive/Spark SQL dialects

**Environment and Execution Notes**:
- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`
- The local MySQL is running at localhost:3306, username `root`, password `root123`
- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)
- The script must include complete table creation (if the target table does not exist) and data writing logic
- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data

## Reference Solution
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
mysql_010 ground truth: 表热度字段数与查询用户数统计TOP排序

Task:
  Filter input table WHERE imp_date = '20260507',
  derive column_count (length of JSON array in column_list) and
  user_count (length of JSON array in user_list),
  sort by heat DESC, column_count DESC, user_count DESC,
  limit 10000, write to output table.
"""
import pymysql
import sys

DB_NAME = "internal_platform_db"
INPUT_TABLE = "sql_heat_column_to_ao_mysql_010"
OUTPUT_TABLE = "sql_heat_column_to_ao_top_mysql_010"

MYSQL_CONFIG = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root123",
    "charset": "utf8mb4",
}

# MySQL equivalent of Spark's size(split(regexp_replace(regexp_replace(regexp_replace(col, '\\[|\\]', ''), '"', ''), ' ', ''), ','))
# In MySQL: strip brackets/quotes/spaces, then count comma-separated items.
# Helper: JSON_LENGTH works for valid JSON arrays; fallback to comma-count.
gt_sql = f"""
INSERT INTO {DB_NAME}.{OUTPUT_TABLE}
    (imp_date, databasename, tablename, column_list, user_list, heat, column_count, user_count)
SELECT
    imp_date,
    databasename,
    tablename,
    column_list,
    user_list,
    CAST(heat AS CHAR) AS heat,
    CAST(JSON_LENGTH(column_list) AS CHAR) AS column_count,
    CAST(JSON_LENGTH(user_list) AS CHAR) AS user_count
FROM {DB_NAME}.{INPUT_TABLE}
WHERE imp_date = '20260507'
ORDER BY heat DESC, JSON_LENGTH(column_list) DESC, JSON_LENGTH(user_list) DESC
LIMIT 10000
"""


def main():
    conn = pymysql.connect(**MYSQL_CONFIG)

    try:
        with conn.cursor() as cur:
            # Ensure output table exists
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (
                    imp_date      VARCHAR(256)  NOT NULL COMMENT '数据日期',
                    databasename  VARCHAR(256)  NOT NULL COMMENT '库名',
                    tablename     VARCHAR(256)  NOT NULL COMMENT '表名',
                    column_list   VARCHAR(256)  NOT NULL COMMENT '热度字段名',
                    user_list     VARCHAR(256)  NOT NULL COMMENT '用户名',
                    heat          VARCHAR(256)  NOT NULL COMMENT '表热度',
                    column_count  VARCHAR(256)  NOT NULL COMMENT '列字段数',
                    user_count    VARCHAR(256)  NOT NULL COMMENT '用户数'
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
            """)

            # Truncate + insert
            cur.execute(f"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}")
            cur.execute(gt_sql)

        conn.commit()

        # Verify row count
        with conn.cursor() as cur:
            cur.execute(f"SELECT COUNT(*) FROM {DB_NAME}.{OUTPUT_TABLE}")
            count = cur.fetchone()[0]
        print(f"mysql_010 ground_truth done: {count} rows written to output table")
    except Exception as e:
        print(f"ground_truth error: {e}", file=sys.stderr)
        conn.rollback()
        sys.exit(1)
    finally:
        conn.close()


if __name__ == "__main__":
    main()