SELECT Where ID in (List of IDs) and limit records of each IDs in MySQL












1















I have a met a situation that I have list of IDs of a Store table and need to fetch latest 10 files from each store.



SELECT * 
FROM tblFiles
WHERE storeId in (IDs)
ORDER BY createdDate DESC
LIMIT 10


But, this limits the whole results. I found an answer to similar SO question. But, the answer recommends to use loop for each ID. This results in multiple DB hit.



Another option is to fetch all records and group them in the code. But, this will be heavy if there's large no.of records.



It'll be nice if it can be handled at the query level. Any help will be appreciated.



NB: The tables used here are dummy ones.










share|improve this question

























  • What version of mysql are you on?

    – P.Salmon
    Dec 31 '18 at 9:57











  • MySQL version 5.6.28

    – Abhishek
    Dec 31 '18 at 10:04











  • checkout this stackoverflow.com/questions/53968285/…

    – Jacob
    Dec 31 '18 at 10:10


















1















I have a met a situation that I have list of IDs of a Store table and need to fetch latest 10 files from each store.



SELECT * 
FROM tblFiles
WHERE storeId in (IDs)
ORDER BY createdDate DESC
LIMIT 10


But, this limits the whole results. I found an answer to similar SO question. But, the answer recommends to use loop for each ID. This results in multiple DB hit.



Another option is to fetch all records and group them in the code. But, this will be heavy if there's large no.of records.



It'll be nice if it can be handled at the query level. Any help will be appreciated.



NB: The tables used here are dummy ones.










share|improve this question

























  • What version of mysql are you on?

    – P.Salmon
    Dec 31 '18 at 9:57











  • MySQL version 5.6.28

    – Abhishek
    Dec 31 '18 at 10:04











  • checkout this stackoverflow.com/questions/53968285/…

    – Jacob
    Dec 31 '18 at 10:10
















1












1








1








I have a met a situation that I have list of IDs of a Store table and need to fetch latest 10 files from each store.



SELECT * 
FROM tblFiles
WHERE storeId in (IDs)
ORDER BY createdDate DESC
LIMIT 10


But, this limits the whole results. I found an answer to similar SO question. But, the answer recommends to use loop for each ID. This results in multiple DB hit.



Another option is to fetch all records and group them in the code. But, this will be heavy if there's large no.of records.



It'll be nice if it can be handled at the query level. Any help will be appreciated.



NB: The tables used here are dummy ones.










share|improve this question
















I have a met a situation that I have list of IDs of a Store table and need to fetch latest 10 files from each store.



SELECT * 
FROM tblFiles
WHERE storeId in (IDs)
ORDER BY createdDate DESC
LIMIT 10


But, this limits the whole results. I found an answer to similar SO question. But, the answer recommends to use loop for each ID. This results in multiple DB hit.



Another option is to fetch all records and group them in the code. But, this will be heavy if there's large no.of records.



It'll be nice if it can be handled at the query level. Any help will be appreciated.



NB: The tables used here are dummy ones.







mysql sql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 31 '18 at 10:17









GMB

11.3k2824




11.3k2824










asked Dec 31 '18 at 9:50









AbhishekAbhishek

708827




708827













  • What version of mysql are you on?

    – P.Salmon
    Dec 31 '18 at 9:57











  • MySQL version 5.6.28

    – Abhishek
    Dec 31 '18 at 10:04











  • checkout this stackoverflow.com/questions/53968285/…

    – Jacob
    Dec 31 '18 at 10:10





















  • What version of mysql are you on?

    – P.Salmon
    Dec 31 '18 at 9:57











  • MySQL version 5.6.28

    – Abhishek
    Dec 31 '18 at 10:04











  • checkout this stackoverflow.com/questions/53968285/…

    – Jacob
    Dec 31 '18 at 10:10



















What version of mysql are you on?

– P.Salmon
Dec 31 '18 at 9:57





What version of mysql are you on?

– P.Salmon
Dec 31 '18 at 9:57













MySQL version 5.6.28

– Abhishek
Dec 31 '18 at 10:04





MySQL version 5.6.28

– Abhishek
Dec 31 '18 at 10:04













checkout this stackoverflow.com/questions/53968285/…

– Jacob
Dec 31 '18 at 10:10







checkout this stackoverflow.com/questions/53968285/…

– Jacob
Dec 31 '18 at 10:10














3 Answers
3






active

oldest

votes


















2














Pre-MySQL 8.0, the simplest method is probably variables:



select f.*
from (select f.*,
(@rn := if(@s = storeId, @rn + 1,
if(@s := storeId, 1, 1)
)
) as rn
from (select f.*
from tblfiles f
where storeId in (IDs)
order by storeId, createdDate desc
) f cross join
(select @s := 0, @rn := 0) params
) f
where rn <= 10;


In MySQL 8+ or MariaDB 10.3+, you would simply use window functions:



select f.*
from (select f.*,
row_number() over (partition by storeid order by createdDate desc) as seqnum
from tblfiles f
) f
where seqnum <= 10;


In older versions of MySQL and MariaDB, the innermost subquery may not be needed.






share|improve this answer


























  • This one is nice. And I think you have to use rn instead of @rn in the last where clause.

    – Abhishek
    Jan 1 at 4:36











  • @Abhishek . . . Yes. That was a typo.

    – Gordon Linoff
    Jan 1 at 13:51



















1














You could workaround it with an UNIONed query, where each subquery searches for a particular id and enforces a LIMIT clause, like :



(SELECT * 
FROM tblFiles
WHERE storeId = ?
ORDER BY createdDate DESC
LIMIT 10)
UNION
(SELECT *
FROM tblFiles
WHERE storeId = ?
ORDER BY createdDate DESC
LIMIT 10)
...


With this solution only one db hit will happen, and you are guarantee to get the LIMIT on a per id basis. Such a SQL can easily be generated from within php code.



Nb : the maximum allowed of UNIONs in a mysql query is 61.






share|improve this answer


























  • This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

    – Abhishek
    Dec 31 '18 at 10:08








  • 1





    @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

    – GMB
    Dec 31 '18 at 10:09





















0














use select in where



SELECT * from tblFiles where storeId in (SELECT id from store ORDER BY datefield/id field desc limit 10)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985995%2fselect-where-id-in-list-of-ids-and-limit-records-of-each-ids-in-mysql%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Pre-MySQL 8.0, the simplest method is probably variables:



    select f.*
    from (select f.*,
    (@rn := if(@s = storeId, @rn + 1,
    if(@s := storeId, 1, 1)
    )
    ) as rn
    from (select f.*
    from tblfiles f
    where storeId in (IDs)
    order by storeId, createdDate desc
    ) f cross join
    (select @s := 0, @rn := 0) params
    ) f
    where rn <= 10;


    In MySQL 8+ or MariaDB 10.3+, you would simply use window functions:



    select f.*
    from (select f.*,
    row_number() over (partition by storeid order by createdDate desc) as seqnum
    from tblfiles f
    ) f
    where seqnum <= 10;


    In older versions of MySQL and MariaDB, the innermost subquery may not be needed.






    share|improve this answer


























    • This one is nice. And I think you have to use rn instead of @rn in the last where clause.

      – Abhishek
      Jan 1 at 4:36











    • @Abhishek . . . Yes. That was a typo.

      – Gordon Linoff
      Jan 1 at 13:51
















    2














    Pre-MySQL 8.0, the simplest method is probably variables:



    select f.*
    from (select f.*,
    (@rn := if(@s = storeId, @rn + 1,
    if(@s := storeId, 1, 1)
    )
    ) as rn
    from (select f.*
    from tblfiles f
    where storeId in (IDs)
    order by storeId, createdDate desc
    ) f cross join
    (select @s := 0, @rn := 0) params
    ) f
    where rn <= 10;


    In MySQL 8+ or MariaDB 10.3+, you would simply use window functions:



    select f.*
    from (select f.*,
    row_number() over (partition by storeid order by createdDate desc) as seqnum
    from tblfiles f
    ) f
    where seqnum <= 10;


    In older versions of MySQL and MariaDB, the innermost subquery may not be needed.






    share|improve this answer


























    • This one is nice. And I think you have to use rn instead of @rn in the last where clause.

      – Abhishek
      Jan 1 at 4:36











    • @Abhishek . . . Yes. That was a typo.

      – Gordon Linoff
      Jan 1 at 13:51














    2












    2








    2







    Pre-MySQL 8.0, the simplest method is probably variables:



    select f.*
    from (select f.*,
    (@rn := if(@s = storeId, @rn + 1,
    if(@s := storeId, 1, 1)
    )
    ) as rn
    from (select f.*
    from tblfiles f
    where storeId in (IDs)
    order by storeId, createdDate desc
    ) f cross join
    (select @s := 0, @rn := 0) params
    ) f
    where rn <= 10;


    In MySQL 8+ or MariaDB 10.3+, you would simply use window functions:



    select f.*
    from (select f.*,
    row_number() over (partition by storeid order by createdDate desc) as seqnum
    from tblfiles f
    ) f
    where seqnum <= 10;


    In older versions of MySQL and MariaDB, the innermost subquery may not be needed.






    share|improve this answer















    Pre-MySQL 8.0, the simplest method is probably variables:



    select f.*
    from (select f.*,
    (@rn := if(@s = storeId, @rn + 1,
    if(@s := storeId, 1, 1)
    )
    ) as rn
    from (select f.*
    from tblfiles f
    where storeId in (IDs)
    order by storeId, createdDate desc
    ) f cross join
    (select @s := 0, @rn := 0) params
    ) f
    where rn <= 10;


    In MySQL 8+ or MariaDB 10.3+, you would simply use window functions:



    select f.*
    from (select f.*,
    row_number() over (partition by storeid order by createdDate desc) as seqnum
    from tblfiles f
    ) f
    where seqnum <= 10;


    In older versions of MySQL and MariaDB, the innermost subquery may not be needed.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 1 at 13:51

























    answered Dec 31 '18 at 11:42









    Gordon LinoffGordon Linoff

    772k35304406




    772k35304406













    • This one is nice. And I think you have to use rn instead of @rn in the last where clause.

      – Abhishek
      Jan 1 at 4:36











    • @Abhishek . . . Yes. That was a typo.

      – Gordon Linoff
      Jan 1 at 13:51



















    • This one is nice. And I think you have to use rn instead of @rn in the last where clause.

      – Abhishek
      Jan 1 at 4:36











    • @Abhishek . . . Yes. That was a typo.

      – Gordon Linoff
      Jan 1 at 13:51

















    This one is nice. And I think you have to use rn instead of @rn in the last where clause.

    – Abhishek
    Jan 1 at 4:36





    This one is nice. And I think you have to use rn instead of @rn in the last where clause.

    – Abhishek
    Jan 1 at 4:36













    @Abhishek . . . Yes. That was a typo.

    – Gordon Linoff
    Jan 1 at 13:51





    @Abhishek . . . Yes. That was a typo.

    – Gordon Linoff
    Jan 1 at 13:51













    1














    You could workaround it with an UNIONed query, where each subquery searches for a particular id and enforces a LIMIT clause, like :



    (SELECT * 
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    UNION
    (SELECT *
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    ...


    With this solution only one db hit will happen, and you are guarantee to get the LIMIT on a per id basis. Such a SQL can easily be generated from within php code.



    Nb : the maximum allowed of UNIONs in a mysql query is 61.






    share|improve this answer


























    • This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

      – Abhishek
      Dec 31 '18 at 10:08








    • 1





      @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

      – GMB
      Dec 31 '18 at 10:09


















    1














    You could workaround it with an UNIONed query, where each subquery searches for a particular id and enforces a LIMIT clause, like :



    (SELECT * 
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    UNION
    (SELECT *
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    ...


    With this solution only one db hit will happen, and you are guarantee to get the LIMIT on a per id basis. Such a SQL can easily be generated from within php code.



    Nb : the maximum allowed of UNIONs in a mysql query is 61.






    share|improve this answer


























    • This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

      – Abhishek
      Dec 31 '18 at 10:08








    • 1





      @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

      – GMB
      Dec 31 '18 at 10:09
















    1












    1








    1







    You could workaround it with an UNIONed query, where each subquery searches for a particular id and enforces a LIMIT clause, like :



    (SELECT * 
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    UNION
    (SELECT *
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    ...


    With this solution only one db hit will happen, and you are guarantee to get the LIMIT on a per id basis. Such a SQL can easily be generated from within php code.



    Nb : the maximum allowed of UNIONs in a mysql query is 61.






    share|improve this answer















    You could workaround it with an UNIONed query, where each subquery searches for a particular id and enforces a LIMIT clause, like :



    (SELECT * 
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    UNION
    (SELECT *
    FROM tblFiles
    WHERE storeId = ?
    ORDER BY createdDate DESC
    LIMIT 10)
    ...


    With this solution only one db hit will happen, and you are guarantee to get the LIMIT on a per id basis. Such a SQL can easily be generated from within php code.



    Nb : the maximum allowed of UNIONs in a mysql query is 61.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 31 '18 at 10:08

























    answered Dec 31 '18 at 10:05









    GMBGMB

    11.3k2824




    11.3k2824













    • This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

      – Abhishek
      Dec 31 '18 at 10:08








    • 1





      @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

      – GMB
      Dec 31 '18 at 10:09





















    • This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

      – Abhishek
      Dec 31 '18 at 10:08








    • 1





      @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

      – GMB
      Dec 31 '18 at 10:09



















    This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

    – Abhishek
    Dec 31 '18 at 10:08







    This one is nice. But, the query becomes a large one if there are more no.of of IDs (storeId) are there in request.

    – Abhishek
    Dec 31 '18 at 10:08






    1




    1





    @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

    – GMB
    Dec 31 '18 at 10:09







    @Abhishek : 61 UNIONs is the max. Query is large but easy to generate dynamically...

    – GMB
    Dec 31 '18 at 10:09













    0














    use select in where



    SELECT * from tblFiles where storeId in (SELECT id from store ORDER BY datefield/id field desc limit 10)





    share|improve this answer




























      0














      use select in where



      SELECT * from tblFiles where storeId in (SELECT id from store ORDER BY datefield/id field desc limit 10)





      share|improve this answer


























        0












        0








        0







        use select in where



        SELECT * from tblFiles where storeId in (SELECT id from store ORDER BY datefield/id field desc limit 10)





        share|improve this answer













        use select in where



        SELECT * from tblFiles where storeId in (SELECT id from store ORDER BY datefield/id field desc limit 10)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 10:14









        RamRam

        397




        397






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985995%2fselect-where-id-in-list-of-ids-and-limit-records-of-each-ids-in-mysql%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas