开发者

MySQL IF conditions and internationalization

开发者 https://www.devze.com 2023-01-08 17:48 出处:网络
I\'m wondering the following, the query below will select the appropriate fields if a language is set.

I'm wondering the following, the query below will select the appropriate fields if a language is set.

First question, I need the fields, title, keywords and description from the pages table or, if the language matches and the field is not null the page_langs table. Now I do this with three IF statements, is it possible to do this in a single IF?

Below query works and the array returned is something like this:

Array ( [0] => Array ( [Page] => Array ( [id] => 2 [lft] => 2 [rght] => 7 ) [0] => Array ( [title] => Welcome [keywords] => welcome [description] => welcome ) ) ) 

So, the id, lft, and rght are 'within the Page (-> pages AS Page) array', the title, keywords and description are outside the Page array, makes sense offcourse, but how do I get those three fields within the Page array, so I can use arr[Page][title] to retrieve the title instead arr[0][title]?

$sql = "SELECT Page.id, Page.lft, Page.rght, 
                IF (STRCMP(Lang.title, '') AND 
                    !STRCMP(Lang.langident, '{$lang}'), Lang.title, Page.title) AS title,
                IF (STRCMP(Lang.keywords, '') AND 
                    !STRCMP(Lang.langident, '{$lang}'), Lang.keywords, Page.keywords) AS keywords,
                IF (STRCMP(Lang.description, '') AND 
                    !STRCMP(Lang.langident, '{$lang}'), Lang.description, Page.description) AS description
            FROM pages AS Page 
                LEFT JOIN page_langs AS Lang
            ON Lang.parent_id = Page.id AND Lang.langident = '{$lang}'
                WHERE Page.id = {$id}开发者_StackOverflow社区"

Any help (suggestions about the query maybe?) appreciated.


I need the fields, title, keywords and description from the pages table or, if the language matches and the field is not null the page_langs table.

SELECT
  COALESCE(Lang.title, Page.title) AS title
  /* ... etc ... */
FROM
  pages AS Page 
  LEFT JOIN page_langs AS Lang ON Lang.parent_id = Page.id 
                                  AND Lang.langident = '{$lang}'
WHERE
  Page.id = {$id}

Since you left-join against the page_langs table with the correct language only, there is no need to check the language code again in the SELECT expression.

If the translation is there, it will be the correct language right away. If the correct language is missing, it will be NULL, hence COALESCE() is sufficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消