Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define own aggregate function in Mysql for GROUP BY?

I have a products table with product names in different languages:

product-id | lang-no | name

I want to list each product once, but using a different language name.

I dont't have all languages for all product names, so I have to fall back onto another language sometimes.

To pick the language with the lowest or highest number I use

SELECT * FROM products JOIN
(SELECT product-id, MIN(lang-no) AS minlang FROM products GROUP BY product-id)
AS u ON products.product-id = u.product-id AND products.lang-no=minlang

But now I need to define another aggregate function instead of MIN or MAX so I can prefer lang-no 3 for example.

How do i define my own aggregate function in Mysql, eg. some IF logic ?

like image 495
Gene Vincent Avatar asked May 07 '17 07:05

Gene Vincent


People also ask

Can we use aggregate function with GROUP BY clause in mysql?

The GROUP BY clause is often used with an aggregate function to perform calculations and return a single value for each subgroup.

Can we use aggregate function in GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do you apply the aggregate function to a group of sets?

Explanation: We apply the aggregate function to a group of sets of tuples using the group by clause. The group by clause must always be used whenever we are willing to apply the aggregate function to a group of sets of tuples.

Which clause is used with an aggregate functions GROUP BY?

The GROUP BY clause is normally used along with five built-in, or "aggregate" functions. These functions perform special operations on an entire table or on a set, or group, of rows rather than on each row and then return one row of values for each group.


1 Answers

You can use case with aggregates to specify which value to return if present and if not min (or max) value:

select p.*
from products p
join (
    select product_id,
        case 
            when sum(lang_no = 3) > 0
                then 3
            else min(lang_no)
            end as min_lang_no
    from products
    group by product_id
    ) p2 on p.product_id = p2.product_id
    and p.lang_no = p2.min_lang_no
like image 181
Gurwinder Singh Avatar answered Sep 29 '22 06:09

Gurwinder Singh