子查询中出现ORA-00942错误

时间:2018-05-29 13:11:18

标签: sql oracle

嘿,我有这个选择:

SELECT *
FROM
  (SELECT *
  FROM
    ( SELECT COUNT(LOGIN) AS COUNT_LOGIN,login FROM COMMENTS GROUP BY login
    ) LIST2
  WHERE COUNT_LOGIN=
    (SELECT MAX(COUNT_LOGIN) FROM LIST2
    )
  ) LIST1
INNER JOIN SYSTEM_USER
ON SYSTEM_USER.LOGIN=LIST1.login ;

我在这一行WHERE COUNT_LOGIN=(SELECT MAX(COUNT_LOGIN) FROM LIST2)

得到** ORA-00942 **

有人可以解释一下为什么这个子查询不能识别LIST2吗?

3 个答案:

答案 0 :(得分:0)

您需要subquery形式的having条款而不是where条款

SELECT login 
FROM COMMENTS 
GROUP BY login
HAVING COUNT(LOGIN) = (SELECT MAX(COUNT_LOGIN) 
                       FROM (SELECT login, COUNT(LOGIN) AS COUNT_LOGIN
                             FROM COMMENTS 
                             GROUP BY login
                            )
                      );

但是,窗口功能也会有所帮助。

SELECT u.*
FROM SYSTEM_USER u
WHERE login = (SELECT Login
               FROM COMMENTS 
               ORDER BY COUNT(*) OVER(PARTITION BY Login) DESC
               FETCH FIRST 1 ROW ONLY
               );

答案 1 :(得分:0)

要获得与您可以使用的大多数评论相关联的登录信息:

SELECT *
FROM SYSTEM_USER su
WHERE su.login IN (SELECT Login
                   FROM Comments
                   ORDER BY COUNT(*) OVER(PARTITION BY Login) DESC
                   FETCH FIRST 1 ROW ONLY);

为避免代码重复,您可以使用CTE:

WITH cte AS (
  SELECT login, COUNT(LOGIN) AS cnt
  FROM COMMENTS 
  GROUP BY login
)
SELECT *
FROM cte
WHERE cnt = (SELECT MAX(cnt) FROM cte);

答案 2 :(得分:0)

我认为您的查询结构不是很好。 我知道您希望获得与max(count_login)匹配的所有登录信息。 为什么不尝试这样做(我没有经过测试,所以查询可能有一些错字)

select cmt.*, su.*
from 
  (select max(count_login) max_count_login from comments) mcl
  join (select count(login) as count_login, login from comments group by login) cmt
    on mcl.max_count_login=cmt.count_login
  join system_user su
    on su.login=cmt.login

正如其他用户所说,你可以使用更好的CTE内存表或一些窗口函数,但如果你不熟悉这些选项,我认为这个解决方案会更容易理解。