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

Python MySQL行转列后输出值全为None的问题求助

解决MySQL行转列后查询Person C为NULL行返回全None的问题

嘿,我一眼就发现你的问题出在SQL语句的字符串匹配错误上!你看,表中存储的name是'Person A'、'Person B'、'Person C'(带空格),但你的case判断里写的是'PersonA'、'PersonB'、'PersonC'(没有空格),这就导致所有case分支都匹配不到,最终返回的全是NULL(在Python里显示为None)。

另外你插入数据时Person C的A2字段是None(对应SQL的NULL),修正SQL后就能正确筛选出这一行。

下面是修正后的完整代码:

import mysql.connector
db = mysql.connector.connect(
 host="localhost",
 port="3307",
 user="root",
 passwd="#",
 database="#"
)
mycursor = db.cursor()
# 先检查表是否存在,避免重复创建报错(可选优化)
mycursor.execute("DROP TABLE IF EXISTS trial157")
mycursor.execute("CREATE TABLE trial157 (Name TEXT(13) NULL , A1 TEXT(13) NULL , A2 TEXT(13) NULL , A3 TEXT(13) NULL , A4 TEXT(13) NULL)")
sql = "INSERT INTO trial157(Name, A1, A2, A3, A4) VALUES (%s, %s, %s, %s, %s)"
val = [
 ('Person A', 'C', 'T', 'R', 'S'),
 ('Person B', 'M', 'V', 'R', 'S'),
 ('Person C', 'M', None , 'R', 'C')
]
mycursor.executemany(sql, val)
db.commit()
# 修正后的SQL:name匹配加上空格,同时格式化语句提升可读性
mycursor.execute("""
SELECT * 
From (
    select name_new, 
           max(case when name = 'Person A' then A end) as PersonA, 
           max(case when name = 'Person B' then A end) as PersonB, 
           max(case when name = 'Person C' then A end) as PersonC 
    from (
        select name, 'A1' name_new, A1 A from trial157 
        union all 
        select name, 'A2' name_new, A2 A from trial157 
        union all 
        select name, 'A3' name_new, A3 A from trial157 
        union all 
        select name, 'A4' name_new, A4 A from trial157 
    ) t 
    group by name_new
) t 
where PersonC is null
""")
myresult = mycursor.fetchall()
for x in myresult:
 print(x)

修正后的输出:

('A2', 'T', 'V', None)

这样就精准筛选出了Person C的A2字段为NULL的行,其他行因为Person C对应字段有值,所以不会被返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:23:43