w*********r 发帖数: 6 | 1 有四个表,
第一个表a 记录有id, name
第二个表b 记录有id, name
第三个表c 记录有id, name
第四个表有4
id1, type1, id2, type2
type1和type2都是'a'或'b'或'c'
如果相应的type是a, 那就可以用id在对应的表中查name。因为name 有可能会变,所以这
么设计了这些表。
问题是显示的时候要
name1(通过id1&type1查), name2(通过id2&type2查),
不知道怎么写一个效率高点的sql。或者好看一点的。请大家指教。多谢。 | c******r 发帖数: 512 | 2
这
select u1.name, u2.name
from
(
select 'a' as t, id, name from a
union all
select 'b' as t, id, name from b
union all
select 'c' as t, id, name form c
) as u1,
(
select 'a' as t, id, name from a
union all
select 'b' as t, id, name from b
union all
select 'c' as t, id, name form c
) as u2,
d
where
u1.id = d.id and u1.t = d.type
and u2.id = d.id and u2.t = d.type
You can create a view of the union so your sql looks better.
If your sql support inline view, (with ...)
【在 w*********r 的大作中提到】 : 有四个表, : 第一个表a 记录有id, name : 第二个表b 记录有id, name : 第三个表c 记录有id, name : 第四个表有4 : id1, type1, id2, type2 : type1和type2都是'a'或'b'或'c' : 如果相应的type是a, 那就可以用id在对应的表中查name。因为name 有可能会变,所以这 : 么设计了这些表。 : 问题是显示的时候要
| m**h 发帖数: 69 | 3 not always 效率高, and with a small flaw
以
【在 c******r 的大作中提到】 : : 这 : select u1.name, u2.name : from : ( : select 'a' as t, id, name from a : union all : select 'b' as t, id, name from b : union all : select 'c' as t, id, name form c
| m**h 发帖数: 69 | 4 another option in oracle syntax:
select
nvl((select a.name from a where d.type1='a' and a.id=d.id1),'') ||
nvl((select b.name from b where d.type1='b' and b.id=d.id1),'') ||
nvl((select c.name from c where d.type1='c' and c.id=d.id1),'')
name1
,
nvl((select a.name from a where d.type2='a' and a.id=d.id2),'') ||
nvl((select b.name from b where d.type2='b' and b.id=d.id2),'') ||
nvl((select c.name from c where d.type2='c' and c.id=d.id2),'')
name2
from d
where
.....
;
Warning: will return '' not N
【在 m**h 的大作中提到】 : not always 效率高, and with a small flaw : : 以
| y****i 发帖数: 5690 | 5 I think there should be an assumption that d.id is valid.
,
【在 m**h 的大作中提到】 : another option in oracle syntax: : select : nvl((select a.name from a where d.type1='a' and a.id=d.id1),'') || : nvl((select b.name from b where d.type1='b' and b.id=d.id1),'') || : nvl((select c.name from c where d.type1='c' and c.id=d.id1),'') : name1 : , : nvl((select a.name from a where d.type2='a' and a.id=d.id2),'') || : nvl((select b.name from b where d.type2='b' and b.id=d.id2),'') || : nvl((select c.name from c where d.type2='c' and c.id=d.id2),'')
|
|