在 Python MySQL 中输出时未定义值?

问题描述

在之前提出的问题的帮助下,请参阅 (How to correctly convert SQL rows to columns?),我正在尝试应用到用 Python 编写的 MysqL 连接器脚本。正如@Popeye 的小提琴 http://sqlfiddle.com/#!9/997790/25 所见,我现在尝试使用 Person C 的空值返回所有行,但其输出如下

import MysqL.connector

db = MysqL.connector.connect(
     host="localhost",port="3307",user="root",passwd="#",database="#"
  )
mycursor = db.cursor()
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)"
val = [
  ('Person A','C','T','R','S'),('Person B','M','V',('Person C',None,'C')
]
mycursor.executemany(sql,val)
db.commit()


mycursor.execute("SELECT * From (select name_new,max(case when name = 'PersonA' then A end) as PersonA,max(case when name = 'PersonB' then A end) as PersonB,max(case when name = 'PersonC' 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)
 - OUTPUT
('A1',None)                                                                                     
('A2',None)
('A3',None)
('A4',None)
[Finished in 1.2s]

解决方法

您使用了错误的名称。(在 case 表达式中使用的名称没有 space。您应该使用与 val 完全相同的名称)

替换

max(case when name = 'PersonA' then A end) as PersonA

max(case when name = 'Person A' then A end) as PersonA

参见 spacePersonA 之间的 name。对 Person BPerson C

执行相同操作