Writing a Complex MySQL Query

前端 未结 3 944
误落风尘
误落风尘 2021-01-17 06:26

Note: you can find my previous question and its answer here - MySQL: Writing a complex query


I have 3 tables.

Table Words_Learned contains

3条回答
  •  不要未来只要你来
    2021-01-17 06:47

    So, I think this is it. You want to get the "best" 100 articles, where "best" means the later a word learnt it contains the better it is. So I look for each article's last learnt word (the max(words_learned.order) per article). Then I show the article IDs in that order and stop at 100.

    select w.idarticle, max(l.`order`)
    from words w
    join words_learned l on l.idwords = w.idwords and l.userid = 123
    group by w.idarticle
    order by max(l.`order`) desc
    limit 100;
    

    You have edited your request. You want to limit the results to articles that contain no more then ten unknown words. In order to do so you must now outer-join the learnt words, so you can count the unknown words (i.e. the outer-joined records). Use HAVING to remove undesired articles from the list.

    select w.idarticle, max(l.`order`)
    from words w
    left join words_learned l on l.idwords = w.idwords and l.iduser = 123
    group by w.idarticle
    having sum(l.idwords is null) <= 10 and max(l.`order`) is not null
    order by max(l.`order`) desc
    limit 100;
    

提交回复
热议问题