仅当单元格不为空时,SQL查询才包含在CONCAT中

时间:2019-02-20 08:46:15

标签: php sql

我正在使用CONCAT构建一个长字符串,数据库(design_name)中的一个单元格在某些行中是空的(不是NULL,而是空的)。每个单个值都由_分隔 当此单元格为空时,我想忽略该值,因为在这种情况下,我在最终的字符串中有两个__符号。使用CASE进行了迭代,但出现错误。

SELECT CONCAT(year,t,id, ' - ', country, '_', year, '_',value, '_', order, 
CASE WHEN design_name != '' THEN '_', design_name, END '_', customer, '_', order) 
AS customer_projects
FROM projects WHERE customer = 'SAMPLE_CUSTOMER' 
ORDER BY id DESC

4 个答案:

答案 0 :(得分:1)

您正在检查design_name是否不等于空,然后将其设置为“ _” 因此,将!=修改为=即可使其正常工作。下面的代码

SELECT CONCAT(year, t,id,  ' - ', isnull(country,''), '_', year, '_',
isnull(value,''), '_', isnull(order,''), 
CASE WHEN design_name = '' THEN '_' 
     ELSE design_name END '_', 
     isnull(customer,''), '_', isnull(order,'')) AS customer_projects
FROM projects WHERE customer = 'SAMPLE_CUSTOMER' 
ORDER BY id DESC

如果项目表中的字段-国家/地区,价值,订单,客户允许为空,则建议对它们使用非空值检查。如果您在查询中获得null值,则CONCAT函数将返回null且查询将失败。

答案 1 :(得分:1)

在MySQL中,您的CASE语句错误

更改此

CASE WHEN design_name != '' THEN '_', design_name, END

CASE WHEN design_name = '' THEN '_' ELSE design_name END,

答案 2 :(得分:0)

您的案例陈述有误

SELECT CONCAT(year,t,id, ' - ', country, '_', year, '_',value, '_', order, 
CASE WHEN design_name = '' THEN '_' else design_name END,  '_', customer, '_', "order") 
AS customer_projects
FROM projects WHERE customer = 'SAMPLE_CUSTOMER' 
ORDER BY id DESC

答案 3 :(得分:0)

在MySQL中,我将使用CONCAT_WS实现此目标,如下所示,CONCAT_WS将在每个值之间添加第一个参数,而忽略NULL值

SELECT CONCAT_WS('_',CONCAT(year,t,id), country, year,value, order,(CASE WHEN design_name = '' THEN NULL ELSE design_name END), customer, order) AS customer_projects
FROM projects WHERE customer = 'SAMPLE_CUSTOMER' 
ORDER BY id DESC