Mysql – Which row is selected by DISTINCT

distinctMySQLselect

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

product-id | lang-no | name

Now I want to generate product lists with names in each language. Unfortunately I don't have all names in all languages and must fall back to other languages if the right one isn't availabe.

Getting a list with a name in any language is easy:

SELECT DISTINCT product-id, name FROM mytable;

Is it defined which row gets picked by the database for the distinct product-id ? (MySQL in my case.)

How can I generate a list for language 1 and one for language 2 ?

Bonus: Can I define which language to fall back on ?

Update:

So my initial query is wrong. (Thanks!)

My list needs to include all products.

SELECT DISTINCT product-id FROM mytable

Now I need to add the names, preferrablx in one language, but no one language covers all products.

Best Answer

Your query will give all unique combinations of product-id and name in the table, so if for example product id 123 has name "Pencil" in English and "Crayon" in French, you will get:

123 | Pencil
123 | Crayon

The results are deterministic in that all unique combinations that exist in your table, will be returned in that query. There isn't an option of which row will be picked, as the list of columns in the query determines what you want the results to be "unique" by. For example if you have product ID 123 with "Pencil" in both British English and American English, the query will return just the single one 123 - Pencil.

To get a list for language 1 (let's say I want it in English and that is language number 567):

select distinct product-id, name from mytable where lang-no = 567

Please clarify how the "fallback" language should work - do you have a specific language in which you know you will always have ALL products? Once you clarify that we can edit the answer accordingly.