我有这两个表:
Org_Extra_Attr
org_id attr_name attr_path
1 desk_name str1
1 citizen bool1
2 perm_user bool1
3 skype_id str1
3 twitter str2
User_Attr_Values
org_id user_id str1 str2 str3 str4 bool1 bool2 bool3 bool4
1 1 b1d07 null null null 1 null null null
1 2 b2d01 null null null 0 null null null
2 3 null null null null 1 null null null
2 4 null null null null 1 null null null
3 5 sam_sky sam_twt null null null null null null
3 6 tom_sky tom_twt null null null null null null
所以,这里的事情是每个 org.can 定义最多 4 个额外的 String 和 Boolean 类型的属性,Org_Extra_Attr 表就像元数据。例如,org_id 1 已经定义了desk_name,它将是str1 对其用户的值,而org_id 3 具有skype_id,它将是str1 对其用户的值。
这可能是一个糟糕的设计,但就目前而言,我需要获取给定 org_id 的用户属性名称和值。就像 org_id = 1 一样,我需要一个 SQL 查询结果(不是第三个表),如下所示:
user_id attr_name val
1 desk_name b1d07
1 citizen 1
2 desk_name b2d01
2 citizen 0
对于 org_id = 3
user_id attr_name val
5 skype_id sam_sky
5 twitter sam_twt
6 skype_id tom_sky
6 twitter tom_twt
最佳答案
像这样的东西
select
t2.user_id,
t1.attr_name,
CASE
WHEN t1.attr_path='str1' then t2.str1
WHEN t1.attr_path='str2' then t2.str2
WHEN t1.attr_path='str3' then t2.str3
WHEN t1.attr_path='str4' then t2.str4
WHEN t1.attr_path='bool1' then t2.bool1
WHEN t1.attr_path='bool2' then t2.bool2
WHEN t1.attr_path='bool3' then t2.bool3
WHEN t1.attr_path='bool4' then t2.bool4
END attr_value
FROM org_Extra_attr t1 inner join User_Attr_Values t2
on t1.org_id = t2.org_id
where t1.org_id=1
关于SQL使用一个表中的列值作为另一个表的列来获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48560410/