简体   繁体   中英

SQL comparison condition column to choose the table to JOIN

GENERAL table:

| id | name | type_id |

SECONDARY1 table:

| id | general_id | erynda_kakayato | byaka |

SECONDARY2 table:

| id | general_id | konkretnaya_hren |

How to combine GENERAL table and one of the SECONDARY using the value of the column to GENERAL.TYPE_ID? The following query does not work, but the logic should be like this.

SELECT * 
FROM GENERAL  
   JOIN (CASE WHEN types_id = 1 THEN  'SECONDARY1' 
              WHEN types_id = 2 THEN  'SECONDARY2' END) AS t  
      ON GENERAL.id = t.id

This request is necessary because values of type changing table for the join. Use of the same table impossible because the property and the number of columns in different tables depending on the column type GENERAL.

Try this:

SELECT g.* 
FROM GENERAL AS g
LEFT JOIN SECONDARY1 AS s1 
   ON CASE WHEN g.type_id = 1 THEN g.id END = s1.general_id
LEFT JOIN SECONDARY2 AS s2
   ON CASE WHEN g.type_id = 2 THEN g.id END = s2.general_id

If type_id = 1 then only the first LEFT JOIN operation is essentially performed, because the ON clause of the second LEFT JOIN becomes NULL = s2.general_id , which can never evaluate to true .

You need to select the value in the select . If using left join , you can choose the first non- NULL value:

select g.*, coalesce(s1.erynda_kakayato, konkretnaya_hren)
from general g left join
     secondary1 s1 
     on s1.general_id = g.id and g.type_id = 1 left join
     secondary s2
     on s2.general_id = g.id and g.type_id = 2 ;

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