Select using dynamically generated tablename

前端 未结 2 1606
说谎
说谎 2021-01-15 22:01

I\'ve got the following problem. My table (geo_table) structure is as follows:

foreign_table_id | foreign_table_name | some_other_fields...
         


        
2条回答
  •  执念已碎
    2021-01-15 22:36

    If you know all possible table names then you can implement it using conditional syntax:

    SELECT foreign_table_id, foreign_table_name FROM `geo_table` gt
    WHERE 
        CASE gt.foreign_table_name
            WHEN 'table1' THEN 
                EXISTS (
                    SELECT * FROM table1
                    WHERE id = gt.foreign_table_id
                )
            WHEN 'table2' THEN 
                EXISTS (
                    SELECT * FROM table2
                    WHERE id = gt.foreign_table_id
                )
            ELSE
                FALSE
        END
    

提交回复
热议问题