Reputation: 529
I have one of simple DB tables named category:
category.id category.name category.lang
1 'apple' 'en'
1 'manzana' 'es'
1 '' 'de'
1 '' 'it'
Variable:
$default_lang = 'en';
$current_lang = 'it';
I would like to make query that returns category_name field according to $current_lang, but if category.name is empty then should use category.name from $default_lang like this:
SELECT * FROM cat_list
LEFT JOIN category ON cal_list.id = category.id
AND IF(category.name = $current_lang = '', $default_lang, 'No Lang')
Please let me know, how could i fix this query to make it work?
===
Ok now I have a good Idea:
SELECT * FROM cat_list LEFT JOIN category
ON cal_list.id = category.id
AND category_lang IN ($curreng_lang, $default_lang)
AND category_name <> ''
it works fine but should I worry about the "IN" order in case if both languages has name values?
Upvotes: 4
Views: 18469
Reputation: 1012
user1664869, what about this?
SELECT catname=CASE c1.name
WHEN '' THEN c2.name
ELSE c1.name
END
FROM
Category c1
INNER JOIN Category c2 ON c1.lang=$current_lang and c2.lang=$default_lang;
Upvotes: 0
Reputation: 1012
SELECT catname=
CASE name
WHEN '' THEN (select name from Category where lang=$default_lang limit 1)
ELSE name
END
FROM Category where id=$current_lang
Explaination: here Query is using case statement inside select statment, where outer query is using condition "id=$current_lang"
so in select statement it will have name='', so for
catname=
CASE name
WHEN '' THEN (select name from Category where lang=$default_lang limit 1)
ELSE name
END
name is '', so first condition with when should execute here it will execute query
(select name from Category where lang=$default_lang limit 1) name apple is returned (because language is 'en') and that will be sotred to catname variable. which will be returned in result
If it will get value with something for name first time (id=$current_lang) it will return with it.
Upvotes: 3
Reputation: 263933
Is the category.name
NULL or empty string?
If NULL, use COALESCE
(Returns the first non-NULL value in the list)
SELECT category.id,
COALESCE(category.name, $default_lang) name,
COALESCE(category.lang, $current_lang) lang
FROM cat_list
LEFT JOIN category
ON cal_list.id = category.id
If Empty String, Use IF
SELECT category.id,
IF(category.name = '', $default_lang,category.name) name,
IF(category.lang = '', $current_lang,category.lang) lang
FROM cat_list
LEFT JOIN category
ON cal_list.id = category.id
Upvotes: 2