I could not formulate it briefly and clearly, I will try to illustrate with an example.

There is a table And

小褌芯谢斜械褑 袗1 | 小褌芯谢斜械褑 袗2 | 肖谢邪谐 | 校泻邪蟹邪褌械谢褜 

Table B

 校泻邪蟹邪褌械谢褜 | 小褌芯谢斜械褑 袙1 | 小褌芯谢斜械褑 袙2 

Table C

 校泻邪蟹邪褌械谢褜 | 小褌芯谢斜械褑 小1 

It is necessary, depending on the value of the flag from table A (0 or 1, for example), to connect with it either table B or table C, so that the result is as follows:

 小褌芯谢斜械褑 袗1 | 小褌芯谢斜械褑 袗2 | 肖谢邪谐 | 校泻邪蟹邪褌械谢褜 | 小褌芯谢斜械褑 袙1 | 小褌芯谢斜械褑 袙2 袗11 | 袗21 | 0 | 58 | 袙14 | 袙25 袗12 | 袗22 | 0 | 92 | 袙17 | 袙29 

Either way:

 小褌芯谢斜械褑 袗1 | 小褌芯谢斜械褑 袗2 | 肖谢邪谐 | 校泻邪蟹邪褌械谢褜 | 小褌芯谢斜械褑 小1 袗15 | 袗26 | 1 | 82 | 小1 袗18 | 袗28 | 1 | 94 | 小1 

Is it possible to somehow implement it in one request?

  • And if the value of the flag for different lines is different, what result do you expect to get? - msi
  • 2
    Hint: select a, b, c union all select d, e, null - Yura Ivanov

1 answer 1

You can combine all three tables with LEFT JOIN , and in SELECT output the result depending on what value the flag takes

 SELECT A.A1 AS A1, A.A2 AS A2, A.ext_id AS ext_id, A.flag AS flag, (CASE A.flag WHEN 0 THEN B.B1 WHEN 1 THEN A.A1 END) AS par1, (CASE A.flag WHEN 0 THEN B.B2 WHEN 1 THEN NULL END) AS par2 FROM A LEFT JOIN B ON A.ext_id = B.id LEFT JOIN C ON A.ext_id = C.id