equals运算符与in运算符之间的SQL计数函数差异

时间:2019-05-07 13:14:41

标签: mysql sql syntax

此问题与以下hackerrank挑战有关: https://www.hackerrank.com/challenges/challenges/problem

有效的版本返回正确的结果集,而另一个版本返回不完整的结果集,因为count(*)不能按in子句预期的那样工作

两个代码段之间唯一的区别是c_count而不是or的第一子句中的count(*)。

由于c_count等于count(*),因此应该没有语义上的区别。如果count(*) in的语法错误,为什么count(*) =有效?

这有效:

select count(*) as c_count ... having c_count in (select ...) or count(*) = (select ...);

这行不通:

select count(*) as c_count ... having count(*) in  (select ...) or count(*) = (select ...);

这是原始查询。 /**/评论指出了两者之间的区别:

工作:

SELECT h.hacker_id
    ,h.name
    ,count(*) AS c_count
FROM Hackers h
JOIN Challenges c ON h.hacker_id = c.hacker_id
GROUP BY h.hacker_id, h.name
HAVING 
    /*USING c_count ALIAS*/ 
    c_count IN (
        SELECT hacker_c_counts2.c_count2
        FROM (
            SELECT count(*) AS c_count2
            FROM Challenges c2
            GROUP BY c2.hacker_id
            ) AS hacker_c_counts2
        GROUP BY hacker_c_counts2.c_count2
        HAVING count(*) = 1
        )
    OR count(*) = (
        SELECT max(hacker_c_counts.c_count1)
        FROM (
            SELECT count(*) AS c_count1
            FROM Challenges c1
            GROUP BY c1.hacker_id
            ) AS hacker_c_counts
        )
ORDER BY count(*) DESC,  h.hacker_id;

不起作用:

SELECT h.hacker_id
    ,h.name
    ,count(*) AS c_count
FROM Hackers h
JOIN Challenges c ON h.hacker_id = c.hacker_id
GROUP BY h.hacker_id, h.name
HAVING 
    /*USING count(*) directly*/ 
    count(*) IN (
        SELECT hacker_c_counts2.c_count2
        FROM (
            SELECT count(*) AS c_count2
            FROM Challenges c2
            GROUP BY c2.hacker_id
            ) AS hacker_c_counts2
        GROUP BY hacker_c_counts2.c_count2
        HAVING count(*) = 1
        )
    OR count(*) = (
        SELECT max(hacker_c_counts.c_count1)
        FROM (
            SELECT count(*) AS c_count1
            FROM Challenges c1
            GROUP BY c1.hacker_id
            ) AS hacker_c_counts
        )
ORDER BY count(*) DESC, h.hacker_id;

1 个答案:

答案 0 :(得分:0)

尝试此操作.....具有h.c_count。....在c_count之前使用表别名“ h”。

祝你好运。