Why does SELECT results differ between mysql and sqlite?

前端 未结 3 1334
你的背包
你的背包 2021-02-12 13:41

I\'m re-asking this question in a simplified and expanded manner.

Consider these sql statements:

create table foo (id INT, score INT);

insert into foo v         


        
3条回答
  •  暖寄归人
    2021-02-12 14:17

    Have you tried this version? :

    select T1.id, avg(T1.score) avg1
    from foo T1
    group by T1.id
    having not exists (
        select T2.id, avg(T2.score) avg2
        from foo T2
        group by T2.id
        having avg(T2.score) > avg(T1.score));
    

    Also this one (which should be giving same results):

    select T1.*
    from
      ( select id, avg(score) avg1
        from foo 
        group by id
      ) T1
    where not exists (
        select T2.id, avg(T2.score) avg2
        from foo T2
        group by T2.id
        having avg(T2.score) > avg1);
    

    The query can also be handled with derived tables, instead of subquery in HAVING clause:

    select ta.id, ta.avg1
    from 
      ( select id, avg(score) avg1
        from foo
        group by id
      ) ta
      JOIN
      ( select avg(score) avg1
        from foo 
        group by id
        order by avg1 DESC
        LIMIT 1
      ) tmp
      ON tmp.avg1 = ta.avg1 
    

提交回复
热议问题