我是 MySQL 的新手。我不确定我是对的。需要帮助。
我有一个表 survey
,其中包含以下列:
id、source_type、source_id、survey_date_time
。
另外两个表是:
education
有 id, col1, col2, col3
列。
games
有 id, col4, col5, col6
列。
survey
表中的数据:
id source_type source_id survey_date_time
--------------------------------------------------------
100 education 1 2013-07-25 00:00:00
101 games 1 2013-07-25 00:00:00
102 games 2 2013-07-26 00:00:00
103 education 2 2013-07-26 00:00:00
education
表中的数据
id col1 col2 col3
--------------------------------------------
1 col1_data1 col2_data1 col3_data1
2 col1_data2 col2_data2 col3_data2
games
表中的数据
id col4 col5 col6
--------------------------------------------
1 col4_data1 col5_data1 col6_data1
2 col4_data2 col5_data2 col6_data2
我想像这样动态地读取数据:
select * from survey left join {survey.sorce_type} on {survey.sorce_type}.id=survey.source_id where survey.id={given_id}
您可以找到架构 here
提前致谢。
更新:
选择语句将是 survey.*, {survey.sorce_type}.*
而不是 *
谢谢
最佳答案
这应该可以满足您的需求:
SELECT *
FROM survey s
LEFT JOIN eduction e ON s.source_type = 'education' AND e.id = s.source_id
LEFT JOIN games g ON s.source_type = 'games' AND g.id = s.source_id
SQL Fiddle 是 here .
本质上,这会根据 source_type
连接适当的表。所以当它是 education
时,它加入到 eduction
表(你可能在那里有拼写错误),当它是 games
时,它加入到游戏
表。
关于mysql - 动态连接表 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17942840/