首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MySQL:如何使用COALESCE

MySQL:如何使用COALESCE
EN

Stack Overflow用户
提问于 2011-04-10 07:53:29
回答 5查看 43.2K关注 0票数 9

假设我有下表:

代码语言:javascript
运行
复制
TABLE: product
===============================================================================
| product_id | language_id | name           | description                     |
===============================================================================
| 1          | 1           | Widget 1       | Really nice widget. Buy it now! |
-------------------------------------------------------------------------------
| 1          | 2           | Lorem  1       |                                 |
-------------------------------------------------------------------------------

我如何查询它,使其尝试给出namedescription,其中language_id = 2,但如果列包含NULL,则回退到language_id =1?

在上面的示例中,我应该为name获取Lorem 1,为description获取Really nice widget. Buy it now!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-04-10 17:06:17

这个怎么样?

代码语言:javascript
运行
复制
SET @pid := 1, @lid := 2;
SELECT 
    COALESCE(name,(
        SELECT name
        FROM product
        WHERE product_id = @pid AND description IS NOT NULL
        LIMIT 1
    )) name, 
    COALESCE(description,(
        SELECT description
        FROM product
        WHERE product_id = @pid AND description IS NOT NULL
        LIMIT 1
    )) description
FROM product
WHERE product_id = @pid 
    AND (language_id = @lid 
    OR language_id = 1)
ORDER BY language_id DESC
LIMIT 1;

其中:

  • @pid:current product id
  • @lid:current language id null
  • language_id
  • name和/或description的值可能为item =2 item and exist
票数 8
EN

Stack Overflow用户

发布于 2011-04-10 07:59:07

代码语言:javascript
运行
复制
select name, description from product
where product_id = @pid
  and name is not null
  and description is not null
  and (language_id = @lang or language_id = 1)
order by language_id desc

其中@pid是当前的产品id,@lang是当前的语言id。

返回的第一行将包含当前名称和描述。

这假设行language_id = 1的名称或描述中不包含NULL

票数 1
EN

Stack Overflow用户

发布于 2011-04-10 07:59:17

代码语言:javascript
运行
复制
select p2.product_id
      ,coalesce(p2.name, p1.name, 'No name') as name
      ,coalesce(p2.description, p1.description, 'No description') as description
  from product p2
  left join product p1 on(
       p1.product_id = p2.product_id
   and p1.language_id = 1
  )
 where p2.product_id  = 1
   and p2.language_id = 2;

Edit1:

上面的查询假设language=2行存在,但名称/descr可能为null。

编辑2.

我记得最近有人问了一个类似的问题。然后我发现它是you。您需要将产品与翻译分开。这就是让这个查询难以编写的原因。Thomas answer使您可以轻松地执行您想要的操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5608740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档