为派生表选择数据时出现未知列错误

时间:2019-01-30 11:53:08

标签: mysql subquery derived-table

我需要一个查询来创建一个表,该表计算给定字段中每个值的数量,但是由于该表中的数据不足,不得不连接另一个表以获得一个附加值(NName):

Records_table--------------       Name_table---------
Ref    Score     Iteration        Ref      NName
1      High      1                1        Falcon
1      Middle    2                2        Willow
2      Middle    1                3        Lance
2      Middle    2                4        Ranger
2      Low       3
3      Low       1
4      High      1
4      High      2
4      High      3

需要的输出:

NName      High  Middle  Low
Falcon     1     1       0
Willow     0     2       1
Lance      0     0       1
Ranger     3     0       0

这就是我所拥有的: (编辑后,我注意到我留在我的版本中的SELECT字段(“ Ref”)中)

SELECT 
    tc.nname AS NName, 
    COUNT(High) High,
    COUNT(Middle) Middle,
    COUNT(Low) Low
FROM
    (SELECT 
        NName, 'High' High, NULL Middle, NULL Low
    FROM
        records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
    WHERE
        tr.score = 'High'
    UNION ALL 
    SELECT 
       NName, NULL, 'Middle', NULL
   FROM
       records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
   WHERE
       tr.score = 'Middle'
    UNION ALL
    SELECT 
       NName, NULL, NULL, 'Low'
   FROM
       records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
   WHERE
       tr.score = 'Low' ) T 
GROUP BY NName;

这失败,并显示“错误1054(42S22):“字段列表”中的未知列“ NName””

我做错了什么,我需要做些什么?

2 个答案:

答案 0 :(得分:1)

虽然不是严格地问问题(这是一个封闭的问题,@ scaisEdge给出了正确的答案),但我认为结合不是解决问题的最佳方法。考虑条件聚合

select n.ref,n.nname,
          sum(case when score = 'high' then 1 else 0 end) High,
          sum(case when score = 'middle' then 1 else 0 end) middle,
          sum(case when score = 'low' then 1 else 0 end) low
from n 
join r on r.ref = n.ref
group by n.ref,n.nname;

+------+--------+------+--------+------+
| ref  | nname  | High | middle | low  |
+------+--------+------+--------+------+
|    1 | Falcon |    1 |      1 |    0 |
|    2 | Willow |    0 |      2 |    1 |
|    3 | Lance  |    0 |      0 |    1 |
|    4 | Ranger |    3 |      0 |    0 |
+------+--------+------+--------+------+
4 rows in set (0.00 sec)

答案 1 :(得分:0)

您的表别名是T不是tc,则应在主选择中使用T.nname

    SELECT 
            T.`NNAME` AS NName, 
            COUNT(High) High,
            COUNT(Middle) Middle,
            COUNT(Low) Low
    FROM  ( 
        SELECT 
                Ref,`NNAME`, 'High' High, NULL Middle, NULL Low
        FROM  records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
        WHERE tr.score = 'High'
        UNION ALL 
        SELECT 
               Ref,`NNAME`, NULL, 'Middle', NULL
        FROM records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
        WHERE tr.score = 'Middle'
        UNION ALL
        SELECT 
               Ref,`NNAME`, NULL, NULL, 'Low'
        FROM records_table tr
        JOIN name_table tc ON tc.ref = tr.ref
        WHERE tr.score = 'Low' 
    ) T 
    GROUP BY T.`NNAME`;