1

我有 2 张桌子:

STEP
id 
value




SCALE
id 
s1
s2
s3
s4
s5
s6

现在 step.id 是 scale.s1、scale.s2、scale.s3 等的外键我想从 step 中获取 scale.s1-s6 值。我用嵌套选择编写了这个查询。是否可以通过一次选择获得此值?

SELECT (
    SELECT step.val FROM step, scale WHERE step.id = scale.s1 AND scale.id = 1) as v1,(
    SELECT step.val FROM step,scale WHERE step.id = scale.s2 AND scale.id = 1) as v2, (
    SELECT step.val FROM step,scale WHERE step.id = scale.s3 AND scale.id = 1) as v3, (
    SELECT step.val FROM step,scale WHERE step.id = scale.s4 AND scale.id = 1) as v4, (
    SELECT step.val FROM step,scale WHERE step.id = scale.s5 AND scale.id = 1) as v5, (
    SELECT step.val FROM step,scale WHERE step.id = scale.s4 AND scale.id = 1) as v6, (
    SELECT step.val FROM step,scale WHERE step.id = scale.s5 AND scale.id = 1) as v7 ;
4

2 回答 2

0

您可以使用带有MAXand的单个查询来做到这一点CASE

SELECT
  MAX(CASE WHEN scale.s1 = step.id THEN step.val END) v1,
  MAX(CASE WHEN scale.s2 = step.id THEN step.val END) v2,
  MAX(CASE WHEN scale.s3 = step.id THEN step.val END) v3,
  MAX(CASE WHEN scale.s4 = step.id THEN step.val END) v4,
  MAX(CASE WHEN scale.s5 = step.id THEN step.val END) v5,
  MAX(CASE WHEN scale.s6 = step.id THEN step.val END) v6
FROM step, scale
WHERE scale.id = 1

这是小提琴

祝你好运。

于 2013-02-08T20:41:10.180 回答
0

只需多次加入步骤。这是前三个:

select s.id, s1.val as v1, s2.val as v2, s3.val as v3
from scale s
join step s1 on s.s1 = s1.id
join step s2 on s.s2 = s2.id
join step s3 on s.s3 = s3.id
于 2013-02-08T23:39:29.303 回答