首页 新闻 会员 周边

求两个sql语句

0
悬赏园豆:10 [已解决问题] 解决于 2012-05-19 11:41

Building表
ID,Name,BuildingState,BuildingUseType,BuildingDesignPurpose,BuildingAddress
1,xx花园xx栋,0,1, 2,xx市xx区
2,xx花园xx栋,1,0, 0,xx市xx区

CODEVALUE表
CodeType, CodeID, CodeValue
BuildingState ,0, 在建建筑物
BuildingState ,1 ,已竣工建筑物
BuildingUseType, 0, 销售
BuildingUseType ,1, 出租
BuildingUseType ,2,自用
BuildingDesignPurpose,0,综合
BuildingDesignPurpose ,1,商业
BuildingDesignPurpose ,2,厂房
....
单查一个表的ID=1,会的到
1,xx花园xx栋,0,1, 2,xx市xx区


但是我希望得当的是
1,xx花园xx栋,在建建筑物(0),出租(1), 厂房(2),xx市xx区
说明一下:
CODEVALUE表的CodeType是用于标识Building的字段名的,但是Building并不是所有字段都会联系到CODEVALUE表去,例如Name和BuildingAddress就不会,
CODEVALUE表的CodeID,对应的是Building表有对应的字段值,求查询得到想要结果的语句,和修改语句(修改时,用户填入的是字符窜比如:在建建筑,
我要存进数据库时根据CODEVALUE表的值得到CodeID的整型值存进去)
下面给出测试数据:

--> 测试数据:[Building]
if object_id('[Building]') is not null drop table [Building]
create table [Building]([ID] int,[Name] varchar(50),[BuildingState] int,[BuildingUseType] int,
[BuildingDesignPurpose] int,[BuildingAddress] varchar(50))
insert [Building]
select 1,'xx花园xx栋',0,1,2,'xx市xx区' union all
select 2,'xx花园xx栋',1,1,2,'xx市xx区'
--> 测试数据:[CODEVALUE]
if object_id('[CODEVALUE]') is not null drop table [CODEVALUE]
create table [CODEVALUE]([CodeType] varchar(25),[CodeID] int,[CodeValue] varchar(12))
insert [CODEVALUE]
select 'BuildingState',0,'在建建筑物' union all
select 'BuildingState',1,'已竣工建筑物' union all
select 'BuildingUseType',0,'销售' union all
select 'BuildingUseType',1,'出租' union all
select 'BuildingUseType',2,'自用' union all
select 'BuildingDesignPurpose',0,'综合' union all
select 'BuildingDesignPurpose',1,'商业' union all
select 'BuildingDesignPurpose',2,'厂房'
EM_C的主页 EM_C | 初学一级 | 园豆:103
提问于:2012-05-18 16:41
< >
分享
最佳答案
1

这个。。。建议你把CODEVALUE表拆分,不同的状态单独一个表,别把多个状态混在一个表里。

如果按照你这样,你的语句要写成:

select id, name, buildingstate=(select codevalue from codevalue where codetype='buildingstate' and codeid=b.buildingstate), ... from building b

假如你拆分了,那么就可以使用Inner Join的方式。

收获园豆:10
无之无 | 大侠五级 |园豆:5095 | 2012-05-18 16:56

唉。。。这个数据库并不是我设计的,我们只是编码而已,这个说要用到内联和临时表。。。查的按你这方法应该可以,我试试看有没有其他的方法,是在不行只有死写了

EM_C | 园豆:103 (初学一级) | 2012-05-18 17:06

@panyum: 用临时表。。。不是不可以,但这个很没必要,还不如用我给你的方案。

或者用内联:

select id, name, c1.codevalue as buildingstate, c2.codevalue as buildingusetype from building b inner join (select * from codevalue where codetype='buildingstate') c1 on b.buildingstate=c1.codeid inner join (select * from codevalue where codetype='buildingusetype') c2 on b.buildingusetype = c2.codeid
无之无 | 园豆:5095 (大侠五级) | 2012-05-18 17:11

@笨笨蜗牛: 其实我想问下有没有select *。。。。就可以查到的。。这个表有150多个字段,不可能一个一个的打上去吧

EM_C | 园豆:103 (初学一级) | 2012-05-18 18:07

@panyum: 那只能建立一个视图,把代码写上了。这个是没办法的。

无之无 | 园豆:5095 (大侠五级) | 2012-05-18 20:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册