CAST comment_count为INTEGER报错:需将评论计数值转为整数
SQL别名字段CAST报错解决与整数类型统计实现
问题说明
执行SQL时触发报错:Unable to CAST comment_count AS integer: Says comment_count is not a column,需求为统计comments.article_id的数量,命名为comment_count且该字段必须为INTEGER类型。
报错SQL语句
SELECT COUNT (comments.article_id) AS comment_count, CAST(comment_count AS INTEGER) , articles.title, articles.topic, articles.author, articles.created_at, articles.votes,articles.article_img_url, articles.body, comments.article_id FROM articles JOIN comments ON articles.article_id = comments.article_id WHERE articles.article_id = '1' GROUP BY articles.title, articles.topic, articles.author, articles.created_at, articles.body, articles.votes,articles.article_img_url, comments.article_id;
问题原因
SQL执行逻辑中,SELECT子句会先计算所有表达式,再为结果分配别名。因此在同一个SELECT子句里,无法直接引用刚定义的别名comment_count进行CAST操作——此时该别名还未被系统识别为有效列。另外,COUNT()函数本身返回数值类型,但如果需要明确指定为INTEGER,应该直接对COUNT的计算结果做类型转换,而非别名。
正确SQL语句
要实现和目标SQL一致的结果,同时确保comment_count为INTEGER类型,只需直接对COUNT(comments.article_id)进行CAST,再指定别名即可:
SELECT CAST(COUNT(comments.article_id) AS INTEGER) AS comment_count , articles.title, articles.topic, articles.author, articles.created_at, articles.votes,articles.article_img_url, articles.body, comments.article_id FROM articles JOIN comments ON articles.article_id = comments.article_id WHERE articles.article_id = '1' GROUP BY articles.title, articles.topic, articles.author, articles.created_at, articles.body, articles.votes,articles.article_img_url, comments.article_id;
这样既避免了别名引用的报错,又保证comment_count是INTEGER类型,输出结果和目标SQL完全一致。
内容的提问来源于stack exchange,提问作者Garden Darts
相关产品推荐
相关产品推荐

