检索一个表的多个字段并做映射

属性表ATTR里部分结构如下(此表有n条数据)

idname
1
2
3汉族
4其他民族
11外国人

用户属性表USERATTR里部分结构如下

ida1a2a30
12411
2null3null

现在需要检索用户的30个属性对应的名字
方法1:

  • 把select case a1 when c1 then c2 end from tmp1 where a1 =c1) n1改成(case a1 when c1 then c2 end) n1,会报错 missing FROM-clause entry for table
  • 把select case a1 when c1 then c2 end from tmp1 where a1 =c1) n1改成select case a1 when c1 then c2 end from tmp1) n1,会报错 more than one row returned by a subquery used as an expression,因为tmp1有n条数据,去掉where a1 =c1就会按笛卡尔积生成表
  • tmp1的union 可以临时加表里没有的属性
with 
	tmp1 as (select id c1,name c2 from ATTR union select -1,'外星人'),
	tmp2 as (select * from USERATTR)
select id,
	(select case a1 when c1 then c2 end from tmp1 where a1 =c1) n1,
	(select case a2 when c1 then c2 end from tmp1 where a2 =c1) n2,
	...........
from tmp2 --order by id

下面的sql更简单更快。上面的sql的where a1 =c1改成where c1 =a1更容易理解

with 
	tmp1 as (select id c1,name c2 from ATTR union select -1,'外星人'),
	tmp2 as (select * from USERATTR)
select id,
	(select c2 from tmp1 where c1=a1) n1,
	(select c2 from tmp1 where c1=a2) n2,
	...........
from tmp2 --order by id

结果如下

idn1n2n30
1其他民族外国人
2null汉族null

方法2

with 
	tmp1 as (select id c1,name c2 from ATTR),
	tmp2 as (select * from USERATTR)
select id,
	case attribute_value1 when tmp1.c1 then tmp1.c2 end n1,
	...........
from tmp1 inner join tmp2 on 1=1 order by id

结果如下,每个user有n条数据,数据量大时速度很慢

idn1n2n30
1nullnull
1null其他民族null
1
1nullnull外国人
2nullnullnull
2null汉族null
2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值