在使用sql语句中会遇到使用with语句的时候其中一个子查询语句没有值会导致最终的数据查询不到情况,通过给每个子查询语句加一个union可以解决这个问题:
with a as (
select value(Field,0) as BQYE from tableName1 where Field=''
union
select NULL as BQYE from tableName2 fetch first 1 rows only
),
b as (
select value(GZSZZE,0) as LJYE from tableName3 where Field=''
union
select NULL as LJYE from tableName2 fetch first 1 rows only
)
select value(BQYE,0), value(LJYE,0) from a,b order by BQYE nulls last,LJYE nulls last --nulls last是指控制记录让控制排在最后,当然也可以使用nulls first
在进行数据插入的时候经常会出现通过某个条件来判断是否插入数据,通过merge into 可以实现:
merge into tableName1 as px
using (select 1 FROM tableName2 fetch first 1 rows only) as py --子句必须,实际没什么用,tableName2可以是任意一张数据表
on px.Field1=? and px.Field2=? -- 当不满足此条件时会执行插入操作
when not matched then insert
(Field1,Field2,Field3,Field4) values(?,?,?,?)
ELSE IGNORE
*mysql是不支持merge into的用法