如何在Mysql中使用Subquery解决此挑战?

时间:2019-05-05 12:59:50

标签: mysql subquery

我正在尝试通过使用子查询来解决此挑战,我不知道我的代码中的语法有什么错误。

select h.hacker_id, h.name from hackers

        join (
                select s.submission_id, s.hacker_id, s.score, d.score
                        from submissions s
                        join challenges c on c.challenge_id = s.challenge_id and
                                                c.hacker_id = s.hacker_id
                        join diffculty d on c.difficulty_level = d.difficulty_level
                        where (s.score = d.score) 
                        group by s.submission_id

        ) as Result(SubId, HID, D1, D2)

        on h.hacker_id = Result.HID
        having count(Result.SubId) > 1
        order by count(Result.SubId) desc, h.name;


错误:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SubId, HID, D1, D2)

        on h.hacker_id = Result.HID
        having count(R' at line 12

这是挑战的链接:https://www.hackerrank.com/challenges/full-score/problem

1 个答案:

答案 0 :(得分:0)

您可以像这样在表表达式本身中(重新)命名列:

select h.hacker_id, h.name 
from hackers

    join ( -- here you started a "table expression"
            select s.submission_id as SubId, -- renamed here 
                   s.hacker_id as HID,       -- renamed here
                   s.score as D1,            -- renamed here
                   d.score as D2             -- renamed here
            from submissions s
            join challenges c on c.challenge_id = s.challenge_id and
                                 c.hacker_id = s.hacker_id
            join diffculty d on c.difficulty_level = d.difficulty_level
            where (s.score = d.score) 
            group by s.submission_id

    ) as Result on h.hacker_id = Result.HID
group by h.hacker_id -- you need to group if you want to use HAVING
having count(Result.SubId) > 1
order by count(Result.SubId) desc, h.name;