多表查最大键 SQL 那些年我遇见的奇葩需求

4 篇文章 0 订阅
3 篇文章 0 订阅

前几天偶遇奇葩需求,今天记录下来,挑战自己的忍耐极限

客户要求在6个表里查某列字段的最大值有则递增无则新增

规律如下
table1
xxx-xxx-xxx-123456
table2
xxx-xxx-xxx-123456
table3
xxx-xxx-xxx-123456-123
table4
xxx-xxx-xxx-123456-123-123
table5
xxx-xxx-xxx-123456-123-123-123
table6
xxx-xxx-xxx-123456-123-123-123-123

规则就是截取后6位数字+1,但是我百思不得其解 为何要去遍历6张表,不由得把客户家人问候了一遍,他想要,咱就做给他,这里只列出SQL

select top 1 * from (  (select top 1 right(ID,6) 'x' from table1 where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]' order by ID desc)  
UNION (select top 1 left(right(ID,10),6)  'x' from table3  where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]' order by ID desc)  
UNION (select top 1 left(right(ID,14),6)  'x' from  table4  where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]' order by ID desc) 
UNION (select top 1 left(right(ID,18),6) 'x'  from  table5 where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]' order by ID desc)
UNION (select top 1 left(right(ID,22),6) 'x'  from  table6 where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]' order by ID desc) 
UNION (select top 1 right(ID,6) 'x'  from table2 where ID like '{type}-[0-9][0-9][0-9][0-9][0-9][0-9]' order by ID desc )) a order by x desc

type为类型 具体实现就是通过union这个好几年用不了一次的关键字进行合并查询

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值