SQL错误使用多个子查询的字段列表中的未知列

Posted

技术标签:

【中文标题】SQL错误使用多个子查询的字段列表中的未知列【英文标题】:SQL error Unknown column in field list using multiple subquery 【发布时间】:2021-10-18 09:05:28 【问题描述】:

我正在尝试根据列打印文本。我的想法是结合每个职业的所有计数并用一个案例来展示它。但我不确定这段代码有什么问题。由于 sCount 不在字段列表中,因此出现错误。任何帮助表示赞赏。

SELECT  CASE

        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", dCount, " " , Occupation, "s.")
        
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", sCount, " " , Occupation, "s.")
        
        END
FROM (
    SELECT * FROM (
        SELECT COUNT(Occupation) AS dCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Doctor'
    UNION
        SELECT COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Singer'
    ) AS s
) AS m;

// this didnt work either
SELECT  CASE

        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", dCount, " " , Occupation, "s.")
        
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", sCount, " " , Occupation, "s.")
        
        END
FROM (
    SELECT COUNT(Occupation) AS dCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Doctor'
    UNION
    SELECT COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Singer'
) AS m;

【问题讨论】:

UNION 结果集的列名取自第一个 SELECT 语句的列名。 - dev.mysql.com/doc/refman/8.0/en/union.html m 子查询的第一列名称是 dCount。 UNION 中第二个查询的列的别名将被忽略。 谢谢,最简单的解决方法是什么? 【参考方案1】:

你在尝试这样的事情吗:

CREATE TABLE OCCUPATIONS  (
  Occupation varchar(100) );

INSERT INTO OCCUPATIONS  VALUES ('doctor'),('doctor'),
                                ('singer'),('singer'),
                                ('doctor'),('doctor'),
                                ('singer'),('singer'),
                                ('doctor'),('singer'),
                                ('singer'),('singer');




SELECT  CASE
        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", tbl.dCount, " " , Occupation, "s.") 
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", tbl.sCount, " " , Occupation, "s.")        
        END as total_count
FROM (          
SELECT COUNT(Occupation) AS dCount,null as sCount, Lower(Occupation) AS Occupation 
FROM OCCUPATIONS 
WHERE Occupation = 'doctor'
group by Occupation 
union 
SELECT null as tst, COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation 
FROM OCCUPATIONS 
WHERE Occupation = 'singer'
group by Occupation 
      )
as tbl ;

基于我的演示的结果是:

total_count

共有 5 位医生。

一共有7位歌手。

演示:https://www.db-fiddle.com/f/pB6b5xrgPKCivFWcpQHsyE/28

【讨论】:

以上是关于SQL错误使用多个子查询的字段列表中的未知列的主要内容,如果未能解决你的问题,请参考以下文章

VBA/SQL 参数化查询 - 字段列表中的未知列

如何在 MySQL 中使用子查询中的字段?

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

#1054 - '字段列表'中的未知列 'id' - phpMyAdmin

SQL里的子查询

SQL练习 高级子查询