loki3328 2011-12-07 10:27
浏览 272
已采纳

多表判断关联查询

A表(
id int,
idd int,
type int(0,表示B表,1表示C表(state=0),2表示C表(state=1)
)
A表数据
testid idd type
15 1 0
15 2 1
15 3 2

B表(
id int ,
testid int,
name varchar2(100),
leavl varchar2(100),
content varchar2(100)

B表数据
id testid name leavl content
1 15 判断 3 内容

C表(
id int ,
testid int,
state int,
name varchar2(100),
leavl varchar2(100),
content varchar2(100),
title varchar2(200)

C表数据
id testid state name leavl content title
1 15 0 单选 3 单选内容 单选
2 15 1 多选 5 多选内容 多选

我想要的结果如下:
testid idd type name leavl content

15 1 0 判断 3 内容
15 2 1 单选 3 单选内容
15 3 2 多选 5 多选内容
问:如何根据A表的testid,根据type字段判断关联查询B表或C表的name,leavl,content等名字字段?

  • 写回答

1条回答 默认 最新

  • lbinzhang 2011-12-08 15:21
    关注

    不知道你描述的结果写的对不对,我查询的结果如下:
    (
    select c1.testid, a1.idd,a1.type,c1.name,c1.leavl,c1.content from a a1 left join c c1
    on a1.type=c1.state where c1.testid is not null
    )
    union All
    (
    select b1.testid, a1.idd,a1.type,b1.name,b1.leavl,b1.content from a a1
    left join b b1 on a1.id=b1.testid
    and a1.type not in ( select a1.type from a a1 left join c c1 on a1.type=c1.state where c1.testid is not null )
    where b1.testid is not null
    )
    TESTID IDD TYPE NAME LEVAL CONTENT
    15 1 0 单选 3 单选内容
    15 2 1 多选 5 多选内容
    15 3 2 判断 3 内容

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?