1. at_naizan表为奶站表,其中含有该省ID,地区ID,县市ID。
2. ENFORCE为执法机构表,其中包含了该执法机构的执法范围,scope字段,有省级、地级、县级
3. ENFORCEMAN为执法人员表,该表中包含了该人员所属的执法机构ID。
现在查询需求如下:给定一个执法人员,根据该执法人员所属执法机构的执法范围和省、地区、县市ID,查出该执法人员管辖的奶站列表,
执法机构表与奶站表通过地区ID关联时,如果是省级的,只需要关联SHENG_ID,如果是地区级的,需要关联SHENG_ID和DIQU_ID,如果是县级的,
则需要关联SHENG_ID、DIQU_ID、XIAN_ID,根据tom大师给出的方法,在where条件中使用case when来实现这个查询,如下:
SQL> select s.sid
2 from
3 AT_NAIZAN S,
4 ENFORCE E,
5 ENFORCEMAN EM
6 WHERE
7 case when e.scope='省级' and s.provinceid=e.sheng_id then 1
8 when e.scope='地级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id then 1
9 when e.scope='县级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id and s.COUNTYID=e.xian_id then 1
10 else 0
11 end=1
12 and em.enforceid=e.eid
13 and em.eid=3;
SID
----------
58
62
63
72
75
76
77
59
67
73
60
69
61
71
66
68
64
70
65
74
3817
已选择21行。
case when e.scope='省级' and s.provinceid=e.sheng_id then 1
when e.scope='地级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id then 1
when e.scope='县级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id and s.COUNTYID=e.xian_id then 1
else 0
end=1
以上的case when,可以认为是一个函数,当符合相应的条件时,返回1,否则返回0,最后判断是否等于1,
从而巧妙的实现了根据不同的scope来进行不同列的join。
当然,用简单的or也可以实现这个功能:
SQL> select s.sid
2 from
3 AT_NAIZAN S,
4 ENFORCE E,
5 ENFORCEMAN EM
6 WHERE
7 ((e.scope='省级' and s.provinceid=e.sheng_id)
8 or
9 (e.scope='地级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id )
10 or
11 (e.scope='县级' and s.provinceid=e.sheng_id and s.areaid=e.diqu_id and s.COUNTYID=e.xian_id)
12 )
13 and em.enforceid=e.eid
14 and em.eid=3;
SID
----------
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
3817
已选择21行。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10972173/viewspace-721503/
,如需转载,请注明出处,否则将追究法律责任。