Will grouping an ordered table always return the first row? MYSQL

I am writing a query where I group a series of rows to find the MIN value for one of the columns.

I would also like to return other column values ​​associated with the returned MIN string.

eg

ID QTY PRODUCT TYPE
--------------------
1  2   Orange  Fruit
2  4   Banana  Fruit
3  3   Apple   Fruit

If I collect this table by the "TYPE" column and select MIN MIN, it will not return the corresponding product for the MIN row, which in the above case is "Apple".

Adding an ORDER BY clause before grouping seems to solve the problem. However, before I go to this query and include this query in my application, I just wanted to know if this method always returns the correct value. Is this the right approach? I saw several examples of using subqueries, however I also read that this is inefficient.

.

+3
2

ORDER BY , , . , , , . ? , , .

, .

, :

SELECT  product.*, MIN(qty)
FROM    product
GROUP BY
        type
ORDER BY
        qty

, MySQL, / GROUP BY.

, a JOIN, a GROUP BY a PRIMARY KEY, :

SELECT  order.id, order.customer, SUM(price)
FROM    order
JOIN    orderline
ON      orderline.order_id = order.id
GROUP BY
        order.id

order.customer , order.id, .

qty .

, .

:

SELECT  p.*
FROM    (
        SELECT  DISTINCT type
        FROM    product p
        ) pd
JOIN    p
ON      p.id = 
        (
        SELECT  pi.id
        FROM    product pi
        WHERE   pi.type = pd.type
        ORDER BY
                type, qty, id
        LIMIT 1
        )

product (type, qty, id), .

+4

. , -

SELECT ID, COUNT(*) AS QTY, PRODUCT_TYPE 
    FROM PRODUCTS
    GROUP BY PRODUCT_TYPE
    ORDER BY COUNT(*) DESC;

, ( PRODUCT_TYPE), , (*). , . , .

, , MIN, , , (, , , ).

,

0

Source: https://habr.com/ru/post/1772082/


All Articles