一个SQL查询显示父记录及其子记录?

时间:2016-01-12 10:29:34

标签: sql sql-server for-loop while-loop do-while

我有一个树形结构,如下所示

Table1
- Iron
 + Land Vehicle
 + Water Vehicle
 + Air Craft 

Select * from Table1 Where Type = 'Vehicle'  

会给出以下结果。

Land Vehicle
Water Vehicle
Air Craft 

但展开时的实际结构如下图所示,

Table1
- Vehicle
 - Land Vehicle
     Car
     Van
     Bus
 - Water Vehicle
     Boat
     Ship
 - Air Craft 
     Jet
     Helicopter

上面的数据库表看起来像,

Item             Type

King Bed          Bed
Double Bed        Bed
Steel D/Bed    Double Bed
Land Vehicle    Vehicle
Car           Land Vehicle 
Van           Land Vehicle 
Bus           Land Vehicle
Water Vehicle   Vehicle
Boat          Water Vehicle 
Ship          Water Vehicle 
Air Craft       Vehicle
Jet            Air Craft
Helicopter     Air Craft 
Arm Chair       Chair

结果应该是所有车辆,结果应如下所示。

Land Vehicle   
Car           
Van           
Bus          
Water Vehicle   
Boat          
Ship          
Air Craft      
Jet           
Helicopter 

基本上,所需的Query需要做的是选择Vehicle类型的所有内容,然后将结果集作为搜索条件并再次选择。例如,如果有三种类型的车辆,下一步应该是逐一取这三种,并检查这三种车辆下方是否有任何东西。如果有一个接一个地再搜索,直到树结构结束。

2 个答案:

答案 0 :(得分:0)

select distinct(type)
from table1
where type like '%Vehicle%'
or type like '%Craft%';

这样的东西应该可行,但我会在你的桌面设计上工作。类型应该只是说'车辆','床','椅子'等和另一个领域,例如Type2应该有'land','air','water','furniture'或类似的东西。

就个人而言,我将Type1作为'Furniture',而Type2会将其识别为'chair'。

在您最近的评论之后:

select item, distinct(type)
from table1
where type like '%Vehicle%'
where type like '%Craft%';

答案 1 :(得分:0)

Sanjaya Weerakkody,

鉴于数据模型(差)设计,不容易找到一个有效的方法来做你想要的。 你可以申请这样的东西;

with Category AS
(
SELECT DISTINCT [Type] as label, [Type]
FROM table1 WHERE [Type] like '%Vehicle%' OR [Type] like '%Air Craft%')
, 
Aux as
(
    SELECT 0 as auxToOrder,  label, [type] FROM Category
    UNION
    SELECT 1 as auxToOrder , item, [type] FROM Table1 WHERE [Type] like '%Vehicle%' OR [Type] like '%Air Craft%'

)

select auxToOrder, [type], label 
from Aux
Order by [type], auxToOrder

结果

auxToOrder    type    label
0    Air Craft    Air Craft
1    Air Craft    Helicopter
1    Air Craft    Jet
0    Land Vehicle    Land Vehicle
1    Land Vehicle    Bus
1    Land Vehicle    Car
1    Land Vehicle    Van
0    Vehicle    Vehicle
1    Vehicle    Air Craft
1    Vehicle    Land Vehicle
1    Vehicle    Water Vehicle
0    Water Vehicle    Water Vehicle
1    Water Vehicle    Boat
1    Water Vehicle    Ship