MySQL在一个查询中获得多个列关联值

时间:2013-02-08 20:10:13

标签: mysql select field

我有两张桌子:

STEP
id 
value




SCALE
id 
s1
s2
s3
s4
s5
s6

现在step.id是scale.s1,scale.s2,scale.s3等的外键 我想从步骤获得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 ;

2 个答案:

答案 0 :(得分:0)

您可以使用MAXCASE的单个查询来执行此操作:

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

这是Fiddle

祝你好运。

答案 1 :(得分: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