【问题标题】:mysql.connector.errors.DataError: 1242 (21000): Subquery returns more than 1 rowmysql.connector.errors.DataError: 1242 (21000): 子查询返回多于 1 行
【发布时间】:2022-01-24 23:09:23
【问题描述】:

我有这个代码:

query = """SELECT sp.customer_surname, sp.amount, cp.amount, sp.monthly, sp.date_ FROM set_payment7777 sp JOIN customers_payments7777 cp ON cp.customer_VAT = sp.customer_VAT WHERE sp.date_ = (SELECT MAX(date_) FROM set_payment7777 GROUP BY customer_VAT) GROUP BY sp.customer_VAT"""
mycursor.execute(query)
for row in mycursor:
    #do something

但我得到了错误:

mysql.connector.errors.DataError: 1242 (21000): 子查询返回更多 超过 1 行

【问题讨论】:

  • 这是不言自明的。 SELECT MAX(date_) FROM set_payment7777 GROUP BY customer_VAT 通常不会返回单个值。

标签: python mysql


【解决方案1】:

您有多个 customer_VAT,然后您的子查询返回不止一行 .. 为避免这种情况,您可以在子查询上使用连接

query = """SELECT sp.customer_surname, sp.amount, cp.amount, sp.monthly, sp.date_ 
    FROM set_payment7777 sp 
    INNER JOIN customers_payments7777 cp ON cp.customer_VAT = sp.customer_VAT 
    INNER JOIN (
        SELECT MAX(date_) FROM set_payment7777 
        GROUP BY customer_VAT
    ) t on t.customer_VAT =  sp.customer_VAT 
    
    GROUP BY sp.customer_VAT"""

无论如何,您有一个没有聚合功能的主选择,那么您应该避免对 group by 的不当使用。在这种情况下,如果您不需要重复结果,请使用 DISTINCT

query = """SELECT DISTINCT sp.customer_surname, sp.amount, cp.amount, sp.monthly, sp.date_ 
    FROM set_payment7777 sp 
    INNER JOIN customers_payments7777 cp ON cp.customer_VAT = sp.customer_VAT 
    INNER JOIN (
        SELECT MAX(date_) FROM set_payment7777 
        GROUP BY customer_VAT
    ) t on t.customer_VAT =  sp.customer_VAT"""

【讨论】:

  • 这看起来不错,唯一的问题是我收到语法错误:mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax;检查与您的 MySQL 服务器版本相对应的手册,以在第 4 行的 '( SELECT MAX(date_) FROM set_payment7777 ' 附近使用正确的语法
  • 回答更新缺失的 JOIN
  • 我仍然收到一个奇怪的错误:mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 't.customer_VAT' in 'on clause'
  • 更新您的问题并添加您正在使用的确切代码
猜你喜欢
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多