Change the WHERE for a select on only one row depending on the field content
-
22-08-2019 - |
Question
Ok, this may sound a little weird, but what I need to do is simple. I have a list of companies and each one has a description. The site is in 4 languages. My problem comes when I have listed a company in English but the person who is in charge of translating it in French still didn't make the translation, so I have a simple:
SELECT TOP(6)
company.name,
company.description,
company.address
WHERE
langid=1
ORDER BY
company.id DESC
The real query is more complex, but I think it will be easier with this one to understand the problem. What I need to do is, when the description is empty in langid 2 then show me the langid 1 as langid 1 is always the first one that will be added. I don't want to show the description field empty.
Imagine row 1, row 2, row 3 and row 5 have a description for langid 2 but not row 4 and row 6. I need to show langid 2 for the rows containing it but langid 1 for the rows with no description.
I know that I could probably do a while with a @i field incrementing and inserting the results one by one in a temp table, but is there any better way of doing it?
Solution
This will work unless there is lng1.name
etc. (i.e. the English language/fallback variant) missing.
SELECT TOP(6)
COALESCE(lng2.name, lng1.name) [name],
COALESCE(lng2.description, lng1.description) description,
COALESCE(lng2.address , lng1.address ) address
FROM
company lng1
LEFT JOIN company lng2 ON
lng1.id = lng2.id AND
lng1.langid = 1 AND
lng2.langid = 2 /* your "foreign language" id, e.g. a parameter */
WHERE
lng1.id IN (1,2,3,4,5,6) /* or whatever */
ORDER BY
lng1.id DESC
It will also not replace the entire address with the English/fallback version if only part of the localized variant is missing. Only the missing parts will be substituted.