我正在使用MySQL 5.6。
我有一个查询表view_listInvoices
,该表的列state
是1到7的整数,但是到目前为止大部分是NULL
。
我要查询的是此状态,如果是某些值,则显示---
,如果是其他值,则要在描述表descinvoicestate
和JOIN上进行联接显示说明。
State Desired Value
NULL ----
1 descinvoice.description where view_listInvoice.state = descinvoicestate.idx
2 descinvoice.description where view_listInvoice.state = descinvoicestate.idx
3 descinvoice.description where view_listInvoice.state = descinvoicestate.idx
4 ---
5 ---
6 ---
7 descinvoice.description where view_listInvoice.state = descinvoicestate.idx
descinvoicestate
表是id和description列之一,仅此而已。
我当前无法使用的查询是
SELECT
otherColumns...,
(SELECT CASE WHEN `view_listInvoices`.`state` IS NULL OR `view_listInvoices`.`state` IN (4, 5, 6) THEN "---"
ELSE (SELECT `descinvoicestate`.`description`
FROM `view_listInvoices`
JOIN `descinvoicestate`
ON `descinvoicestate`.`idx` = `view_listInvoices`.`state`) END) as 'Prep'
FROM `view_listInvoices`
我不断收到语法错误,但我不知道这是什么错误。帮助吗?
答案 0 :(得分:1)
您应该使用没有嵌套的选择
SELECT
otherColumns...,
CASE WHEN `view_listInvoices`.`state` IS NULL OR `view_listInvoices`.`state` IN (4, 5, 6)
THEN "---"
ELSE `descinvoicestate`.`description`
END prep
FROM `view_listInvoices`
JOIN `descinvoicestate` ON `descinvoicestate`.`idx` = `view_listInvoices`.`stat
或者如果不是表之间的所有行nathc都使用左连接
SELECT
otherColumns...,
CASE WHEN `view_listInvoices`.`state` IS NULL OR `view_listInvoices`.`state` IN (4, 5, 6)
THEN "---"
ELSE `descinvoicestate`.`description`
END prep
FROM `view_listInvoices`
LEFT JOIN `descinvoicestate` ON `descinvoicestate`.`idx` = `view_listInvoices`.`stat
答案 1 :(得分:1)
您不能将SELECT
与CASE .. WHEN
一起使用。另外,您可以在此处使用“相关子查询”。请尝试以下操作:
SELECT
/* otherColumns..., */
CASE WHEN v.`state` IS NULL
OR v.`state` IN (4, 5, 6)
THEN '---'
ELSE ( SELECT d.description
FROM `descinvoicestate` AS d
ON d.`idx` = v.`state`
LIMIT 1 )
END as 'Prep'
FROM `view_listInvoices` AS v
答案 2 :(得分:1)
我将使用LEFT JOIN
和COALESCE()
:
SELECT otherColumns...,
COALESCE(dis.description, '---') as prep
END prep
FROM `view_listInvoices` li LEFT JOIN
`descinvoicestate` dis
ON dis.`idx` = li.`stat;
这是一种很常见的逻辑。