这里有3个表,我想写一个SQL查询来从Table1和Table2获取Table3的值
Table1
| ID | NAME |
+-----+-------+
| 111 | ALPHA |
| 222 | BRAVO |
+-----+-------+
Table2
| NAME_RESULT | STEP_ID | STEP_NAME | STEP_TYPE | STEP_PARENT |
+-------------+---------+-----------+-----------+-------------+
| 111 | aaa | R1 | step2 | 5cf |
| 222 | bbb | R2 | step2 | e7b |
| 333 | ccc | R2 | step2 | 3ac |
| 555 | e4a | C4 | step10 | 51f |
+-------------+---------+-----------+-----------+-------------+
Table2 we find on NAME_RESULT = 222 and STEP_ID = bbb --> STEP_PARENT = e7b Next reusing the previous STEP_ID from first STEP_PARENT values to get new STEP_PARENT :
| NAME_RESULT | STEP_ID | STEP_NAME | STEP_TYPE | STEP_PARENT|
+-------------+---------+------------+-----------+------------+
| 111 | e7b | Measure R | step2 | 89d |
| 777 | 3ac | Measure R | step2 | 5fc |
+-------------+---------+------------+-----------+------------+
对于Table2的下一个查询,我们在STEP_ID = e7b - >上找到了。 STEP_PARENT = 89d
Table3 on t3.IDM = t2.STEP_PARENT = 89d :
| IDM | MEAS |
+-----+-------+
| eee | 10.1 |
+-----+-------+
| 89d | 12.2 |
| 5fc | 7.3 |
+-----+-------+ We find MEAS = 12.2
1)首先查询:
select * from Table1 t1 inner join Table2 t2 on t1.ID = t2.NAME_RESULT
where t2.STEP_NAME = 'R2' and t2.STEP_TYPE = 'step2' and
t1.NAME = 'BRAVO'
- >结果应为STEP_ID = bbb
2)第二次查询:
select * from Table2 t2 where t2.STEP_PARENT = STEP_ID
- >结果应为STEP_ID = e7b
2)第三次查询:
select * from Table2 t2 where t2.STEP_ID = STEP_PARENT
- >结果应为STEP_PARENT = 89d
3)上次查询:
select * from Table3 t3 inner join t2 on t2.STEP_PARENT = t3.IDM
- > MEAS值应为= 12.2
希望它会更明确,所以请告诉我,如果可能的话,如何在一个查询中使用所有内容
感谢您的帮助
答案 0 :(得分:0)
好的,我觉得这个问题很混乱。但希望这是您正在寻找的查询。
select
t3.meas
from
table3 t3
inner join
table2 t2a
on t3.idm = t2a.step_parent
inner join
table2 t2b
on t2a.step_id = t2b.step_parent
inner join
table1 t1
on t2b.name_result = t1.id
where
t1.name = 'BRAVO'
and t2b.step_name = 'R2'
and t2b.step_type = 'step2'
答案 1 :(得分:0)
如果我理解正确,那么这应该有效。
select t3.MEAS from Table1 t1
inner join Table2 t21 on t1.ID = t21.NAME_RESULT
inner join Table2 t22 on t21.STEP_PARENT = t22.STEP_ID
inner join Table3 t3 on t3.IDM = t22.STEP_PARENT
where t21.STEP_NAME = 'R2' and t21.STEP_TYPE = 'step2' and
t1.NAME = 'BRAVO'
答案 2 :(得分:0)
一步一步:
select meas
from table3
where idm =
(
select step_parent
from table2
where step_id =
(
select step_parent
from table2
where name_result =
(
select id
from table1
where name = 'BRAVO'
)
and step_name = 'R2'
and step_type = 'step2'
)
);
如果数据集中可以有多个条目,则可能必须将=
替换为IN
。