SELECT query return 1 row from each group

后端 未结 3 1240
囚心锁ツ
囚心锁ツ 2020-11-27 20:45

This is a product table and have few million of records.

\"enter

I want to lis

相关标签:
3条回答
  • 2020-11-27 21:12

    There are many alternatives to solves this, one which I recommend is to have joined a subquery which separately gets the latest ID (assuming that the column is AUTO_INCREMENTed) for each store_ID.

    SELECT  a.*
    FROM    tableName a
            INNER JOIN
            (
                SELECT  store_ID, MAX(ID) max_ID
                FROM    tableName
                GROUP BY store_ID
            ) b ON a.store_ID = b.store_ID AND
                    a.ID = b.max_ID
    
    • SQLFiddle Demo

    for better performance, be sure to have an index on these columns: ID and store_id.

    UPDATE 1

    if you want to have limit for every records, use this below,

    SELECT ID, product_Name, store_ID
    FROM   tableName a
    WHERE
      (
         SELECT COUNT(*) 
         FROM   tableName b
         WHERE  b.store_ID = a.store_ID AND b.ID >= a.ID
      ) <= 2;
    
    • SQLFiddle Demo
    0 讨论(0)
  • 2020-11-27 21:18

    Try this please:

    SELECT * FROM YOURTABLE B
    JOIN (SELECT MAX(ID) MX FROM YOURTABLE GROUP BY STORE_ID) A
    ON  A.STORE_ID = B.STORE_ID
    AND B.ID = A.MX
    GROUP BY B.STORE_ID
    ;
    
    0 讨论(0)
  • 2020-11-27 21:23
    SELECT store_id,id,product_name FROM table_name
    WHERE id IN (SELECT MAX(id) FROM table_name GROUP BY store_id)
    ORDER BY id
    

    this should work and you can Order by as per your req either by store_id or id.

    0 讨论(0)
提交回复
热议问题