简体   繁体   中英

How to use sub-query result twice in the query?

I have this query:

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 )

As you see there is two identical sub-queries. How can I write that sub-query once and use its result twice?

Use can use 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;

Note that I also removed the if() . This is unnecessary in MySQL where boolean expressions are treated as integers in a numeric context.

An alternative would use IN :

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

No need for two sub-queries here, one is enough, just make sure col1 = col2 and you're done:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM