translate content using where with 2 languages ​​in order (language = "enus" or i18n = "enus")

StackOverflow https://stackoverflow.com/questions/22978520

  •  30-06-2023
  •  | 
  •  

Question

I have a query with subquery to get the translated text, but the where clause not working...
Always returns the text enus because it is the first in the DB even though other languages

How can I do to respect the stated order in the query (language = "enus" or i18n = "enus")
firstly ptbr else or enus

[translate]

key | language | text
1   | enus     | foo in enus
1   | ptbr     | foo in ptbr
1   | it       | foo in it



[query]

select
    A.*,
    ( select text from translate where key = A.key and (language = "ptbr" or i18n = "enus") limit 1 ) `translate`
from table as A
where A.id = 1
Was it helpful?

Solution

Use multiple LEFT JOIN clauses.

SELECT a.*, IFNULL(p.text, e.text) AS text
FROM table AS a
LEFT JOIN translate AS p ON p.key = a.key AND p.language = 'ptbr'
LEFT JOIN translate AS e ON e.key = a.key AND e.i18n = 'enus'

The subquery that will do what you want is:

SELECT text
FROM (SELECT 1 AS priority, text 
      FROM translate
      WHERE key = A.key
      AND language = 'ptbr'
      UNION
      SELECT 2 AS priority, text
      FROM translate
      WHERE key = A.key
      AND i18n = 'enus') x
ORDER BY priority
LIMIT 1

Or you could do:

SELECT text
FROM translate
WHERE key = A.key
AND (language = "ptbr" or i18n = "enus")
ORDER BY language = "ptbr" DESC
LIMIT 1

The general point is that if you want LIMIT 1 to return a preferred row, you need to use ORDER BY to ensure that this row is first in the results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top