我有一个表tbl_expenseLimit
,用于获取给定变量组合的Limit
。
tbl_expenselimit
+------+---------+----------+---------+-------+----------+
| SrNo | ExpType | Location | Expense | Limit | empgrade |
+------+---------+----------+---------+-------+----------+
| 1 | ERA | Metro | 1 | 250 | A |
| 2 | ERA | Metro | 2 | 500 | A |
| 3 | ERA | Metro | 3 | 5000 | A |
+------+---------+----------+---------+-------+----------+
如果主表中的ExpType
为ERA,Location
为Metro,Expense
为1,empgrade
为'A',则Limit
为250 。
如果任何条件不匹配,例如:如果ExpType
为ERA,Expense
为1,则empgrade
为“A”,但Location
为非然后Metro Limit
应为NULL
。同样,如果所有条件都匹配但是升级为'B'(tbl_expenselimit
表中不存在,那么它应该NULL
返回Limit
select other.srno,VoucherId,other.ExpType, lmt.Limit
from tbl_voucherotherexpense other
left join tbl_TypesOfExpenses expensemst
on other.expense=expensemst.srno
left join tbl_expenseLimit lmt
on (other.Expense=lmt.Expense
and other.ExpType=lmt.ExpType
and (( lmt.location is not null
and other.location=lmt.location) or 1=1))
where voucherid='C0000004' and lmt.empgrade='a'
tbl_voucherotherexpense
和tbl_TypesOfExpenses
之间的联接始终会找到匹配项。所以需要关注的只是tbl_expenseLimit
。
我写的查询错了。它没有实现我想要的。任何帮助表示赞赏。
修改
假设在我的主要表ExpType
中 ERA ,Location
是 Metro ,Expense
是 2 但是empgrade
是 B 然后输出应该是:
+------+-----------+---------+-------+
| srno | VoucherId | ExpType | Limit |
+------+-----------+---------+-------+
| 4 | C0000004 | ERA | NULL |
+------+-----------+---------+-------+
或者如果
在我的主要表ExpType
中 ERA ,Location
是 Metro ,empgrade
是 A 但{ {1}} 12 然后输出仍应与上述相同。
答案 0 :(得分:0)
引用您即将加入的表格lmt
的所有条件都应该放在on
中,与where
条款不同,它会赢得&#t} t删除条件不匹配的行:
select other.srno,VoucherId,other.ExpType, lmt.Limit
from tbl_voucherotherexpense other left join tbl_TypesOfExpenses expensemst on other.expense=expensemst.srno
left join tbl_expenseLimit lmt
on other.Expense=lmt.Expense
and other.ExpType=lmt.ExpType
and other.location=lmt.location
and lmt.empgrade='a'
where voucherid='C0000004'