我在表中有三个布尔值列,这些列确定应将哪些值提供给程序。我需要在程序中添加最多3个标签和值。
到目前为止,每个标签和每个值都有8种情况(因为3个布尔标志表示2 ^ 3 = 8个组合)。有没有办法使它更简洁?
例如,对于我的第一个标签,我有
case
WHEN travelExpenseEnabled=0 and otherExpenseEnabled=0 and materialExpenseEnabled = 0 THEN
''
WHEN travelExpenseEnabled=1 and otherExpenseEnabled=0 and materialExpenseEnabled = 0 THEN
'Estimated Travel Expense'
WHEN travelExpenseEnabled=1 and otherExpenseEnabled=1 and materialExpenseEnabled = 0 THEN
'Estimated Travel Expense'
WHEN travelExpenseEnabled=1 and otherExpenseEnabled=0 and materialExpenseEnabled = 1 THEN
'Estimated Material'
WHEN travelExpenseEnabled=1 and otherExpenseEnabled=1 and materialExpenseEnabled = 1 THEN
'Estimated Material'
WHEN travelExpenseEnabled=0 and otherExpenseEnabled=1 and materialExpenseEnabled = 0 THEN
CONCAT('Estimated ', listquotes.otherLabel)
WHEN travelExpenseEnabled=0 and otherExpenseEnabled=1 and materialExpenseEnabled = 1 THEN
'Estimated Material'
WHEN travelExpenseEnabled=0 and otherExpenseEnabled=0 and materialExpenseEnabled = 1 THEN
'Estimated Material'
END as optLabel1,
与第一个值相似。这种方法还意味着我需要在查询的每个部分保持自己的材料层次结构>旅行>其他层次一致,因此如果要求我更改订单,这将很快变得令人头疼。是否可以执行以下操作
case
WHEN travelExpenseEnabled=0 and otherExpenseEnabled=0 and materialExpenseEnabled = 0 THEN
'' as optLabel1,
'' as optLabel2,
'' as optLabel3,
0.00 as estCost1,
0.00 as estCost2,
0.00 as estCost3,
WHEN travelExpenseEnabled=1 and otherExpenseEnabled=0 and materialExpenseEnabled = 0 THEN
'Estimated Travel' as optLabel1,
'' as optLabel2,
'' as optLabel3,
travelExpense as estCost1,
0.00 as estCost2,
0.00 as estCost3
每种情况下etc。这样,我可以仅在8种情况下设置所需的3个值,而不必为每个值进行8种情况。这可能吗?我正在使用MySQL 5.6
答案 0 :(得分:1)
如果您是在用户界面(我假设)上在运行时将其从dB中拉出来的,那么您可能希望提前将数据展平。
我将您的代码放入通用选择视图中,让应用从VIEWNAME中执行SELECT {... columnList ...},其中KEY =变量等
您仍然需要保留和维护代码库,但是它将集中在一个地方。
答案 1 :(得分:1)
我建议参考表或派生表:
select t.*,
ref.optlabel1
from t left join
(select 0 as travelExpenseEnabled, 0 as otherExpenseEnabled, 0 as materialExpenseEnabled, '' as optlabel1 union all
select 1, 0, 0, 'Estimated Travel Expense' union all
...
) ref
on ref.travelExpenseEnabled = t.travelExpenseEnabled and
ref.otherExpenseEnabled = t.otherExpenseEnabled and
ref.materialExpenseEnabled = t.materialExpenseEnabled
您可以在子查询中包括所有想要的标签。