Mysql选择Where和default如果where条件不存在

时间:2016-11-30 20:51:37

标签: mysql selection where

我有表产品和产品详细信息。在productDetails中,我有许多语言的产品描述行(由lang列区分)。并非每种产品都会有各种语言的描述。如何选择将使用指定语言(Where productDescription.lang = 'en')选择描述,并且如果指定的语言不存在,将使用默认语言选择描述(使用默认语言的描述始终存在)。 / p>

我做到了:

select *
  from product
  left join productDetails on product.id = productDetails.product_id
 where productDetails.language = 'en';

我得到了en语言的所有细节。如果en不存在,如何修改此选项以使用默认语言选择详细信息?

1 个答案:

答案 0 :(得分:0)

这样的事情。我不知道你的确切架构:

select 
   p.id, 
   if(IS NULL d2.description, d1.description, d2.description ) `description`
 from product p
 join productDetails d1
   on product.id = productDetails.product_id
      and
   productDetails.language = 'default_lang'
 left join productDetails d2
   on product.id = productDetails.product_id 
      and
   productDetails.language = 'en'