mysql中输出时没有定义值?

f1tvaqid  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(222)

在前面提出的问题see(如何正确地将sql行转换为列?)的帮助下,我正在尝试应用于用python编写的mysql连接器脚本。如@大力水手的小提琴所见http://sqlfiddle.com/#!9/997790/25,我现在尝试返回所有行,其中personc的值为null,但其输出如下所示

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, %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()

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, None, None)                                                                                     
('A2', None, None, None)
('A3', None, None, None)
('A4', None, None, None)
[Finished in 1.2s]
k5ifujac

k5ifujac1#

你用错名字了 case 表达式名称不带 space . 你应该完全按照你的要求使用它 val )
代替

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

具有

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

看到了吗 space 介于 Person 以及 Aname . 对…也一样 Person B 以及 Person C

相关问题