我必须制作这样的可排序表:
可排序表格:
building_id | building_age | title |
-------------------------------------------------
1 | 100 | New york buil |
2 | 50 | House 1 |
3 | 50 | House 10 |
从这些表中:
构建表:
building_id | building_age | building_type_1_FK | building_type_2_FK
---------------------------------------------------------
1 | 100 | null | 1
2 | 50 | 1 | null
3 | 50 | 2 | null
building_type_1 :
type_id | title | diff1 |
-------------------------------------------------
1 | New york buil| blablabla |
building_type_2 :
building_id | title |
----------------------------
1 | House 1 |
2 | House 10 |
3 | House 500 |
在连接这些表时,我得到了几个标题列,其中一个列不为空。有没有办法按标题排序并选择前10个结果而不获取所有数据然后在应用程序中排序?
p.s ..我知道一般来说这种架构并不好,但我无法改变它。
答案 0 :(得分:1)
是。您希望对两个表执行左外连接,然后将结果组合在一起:
select b.building_id, b.building_age, coalesce(bt1.title, bt2.title) as title
from building b left outer join
building_type_1 bt1
on b.building_type_1_FK = bt1.type_id left outer join
building_type_2 bt2
on b.building_type_2_FK = bt2.building_id;
要在Oracle中获得前10名结果:
select *
from (select b.building_id, b.building_age, coalesce(bt1.title, bt2.title) as title
from building b left outer join
building_type_1 bt1
on b.building_type_1_FK = bt1.type_id left outer join
building_type_2 bt2
on b.building_type_2_FK = bt2.building_id
order by title
) b
where rownum <= 10;