查询错误未知列'计数'在'字段列表'

时间:2014-11-10 23:59:45

标签: mysql

我正在尝试对表名中包含house的所有表中的picks列进行求和。

SELECT SUM(Picks) AS A 
  FROM (SELECT TABLE_NAME 
          FROM information_schema.TABLES 
         WHERE TABLE_NAME LIKE '%house' AND 
               table_schema='myschema'
       ) AS T

此SQL语句产生消息

  

“字段列表”中的未知列“Picks”

如果我只查询:

SELECT TABLE_NAME 
  FROM information_schema.TABLES 
 WHERE TABLE_NAME LIKE '%house' AND
       table_schema='myschema'

返回预期的表列表。我已经验证每个返回的表都有一个count列,并且所有数据类型都相同VARCHAR(45)

我缺少什么?

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT SUM(Picks) AS A 
FROM (SELECT TABLE_NAME 
      FROM information_schema.TABLES 
      WHERE TABLE_NAME LIKE '%house' AND 
            table_schema='myschema'
    ) AS T

您缺少的是子查询没有名为Picks的列。我的意思是,以下内容可行:

SELECT SUM(Picks) AS A 
FROM (SELECT TABLE_NAME, 1 as Picks
      FROM information_schema.TABLES 
      WHERE TABLE_NAME LIKE '%house' AND 
            table_schema='myschema'
    ) AS T

或者这个:

SELECT COUNT(*) as Picks
FROM (SELECT TABLE_NAME
      FROM information_schema.TABLES 
      WHERE TABLE_NAME LIKE '%house' AND 
            table_schema='myschema'
    ) AS T

但是在您的查询中,Picks未定义。因此错误。

而且,information_schema.tables中也没有这样的列。这让我觉得你很困惑。也许该列存在于“house”表中。但是,您无法像这样引用表格。如果您确实想要将表名动态地放入查询中,您可能需要调查准备好的语句 - prepare / execute(请参阅here)。