MySQL:如何使用COALESCE

问题描述 投票:9回答:5

说我有下表:

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?

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

mysql coalesce
5个回答
8
投票

怎么样?

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:当前产品ID
  • [@lid:当前语言ID
  • name和/或description的值可以为空
  • language_id = 2个项目不存在

1
投票
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。


0
投票
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行,但是name / descr可以为null。

编辑2。我只是记得最近有人问过类似的问题。然后我发现它是you。您需要将产品与翻译分开。这就是使此查询难以编写的原因。 Thomas answer使您轻松执行所需的操作。


0
投票

这里是与SQL Update一起使用的示例:

类似于Oracle的NVL。您可以像下面这样使用参数在准备好的语句中使用它

UPDATE
    tbl_cccustomerinfo
SET
    customerAddress = COALESCE(?,customerAddress),
    customerName =  COALESCE(?,customerName),
    description =  COALESCE(?,description)
WHERE
    contactNumber=?

0
投票

假设:每个产品都有一个带有language = 1的条目下面的代码只是用于检索所需内容的简单sql。

另一个主题是,如果您想要您要求的行为,..因为您可以在namedescription之间使用多种语言。我将以不同的方式设计它,如果两个字段之一为空,则默认使用主语言(1)。

select p.product_id,
  coalesce(pl.name, p.name, 'No name') as name,
  coalesce(pl.description, p.description, 'No description') as description
from product p
  left join product pl on (pl.product_id = p.product_id and pl.language_id = :language_id)
where p.product_id = :product_id and p.language_id = 1
© www.soinside.com 2019 - 2024. All rights reserved.