如何在查询中使用两次子查询结果?

时间:2016-05-11 11:07:59

标签: mysql sql subquery

我有这个问题:

UPDATE QandA SET accepted = IF ( id <> :answer_id, 0, 1 )
  WHERE col1 = ( SELECT related FROM QandA WHERE id = :answer_id ) AND
        col2 = ( SELECT related FROM QandA WHERE id = :answer_id )

如您所见,有两个相同的子查询。如何编写该子查询一次并使用其结果两次?

2 个答案:

答案 0 :(得分:2)

使用可以使用CROSS JOIN

UPDATE QandA CROSS JOIN
       ( SELECT related FROM QandA WHERE id = :answer_id ) x
    SET accepted = ( id = :answer_id)
WHERE col1 =  x.related AND col2 = x.related;

请注意,我还删除了if()。这在MySQL中是不必要的,其中布尔表达式在数值上下文中被视为整数。

替代方案将使用IN

WHERE ( SELECT related FROM QandA WHERE id = :answer_id ) IN (col1, col2)

答案 1 :(得分:1)

这里不需要两个子查询,一个就足够了,只需确保col1 = col2即可完成:

UPDATE QandA SET accepted = IF ( id <> :answer_id, 0, 1 )
  WHERE col1 = ( SELECT related FROM QandA WHERE id = :answer_id ) AND
        col2 = col1