在MySQL查询中使用列名作为表

时间:2013-07-23 15:51:49

标签: mysql

我有一个数据库,其中一个表中的列是我需要查找相应记录的表名。

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| TABLE questions                                                                                                                                                                                 |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Field                   | Type                                                                                                                                                                  |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| question_id             | int(11)                                                                                                                                                               |
| question_response_table | enum('question_responses_datetime','question_responses_int','question_responses_float','question_responses_bool','question_responses_text','question_responses_enum') |
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

question_response_table列中的每个值都是另一个包含用户响应的表(原始数据库设计要求将响应按数据类型分隔为单独的表)。

我有一个查询,它可以获取我需要的所有内容,除了用户的响应。但出于性能原因,我真的希望将响应添加到同一个查询中(每年DB会显着增长)。以下是我想做的一个例子:

SELECT cr.category_id, cr.category_response_id, r.response 
FROM category_responses AS cr 
JOIN response_key_questions AS rkq ON cr.category_id = rkq.category_id 
JOIN questions AS q ON q.question_id = rkq.question_id
JOIN {q.question_response_table} AS r ON r.category_response_id = cr.category_response_id 
WHERE cr.belongs_to = 4 AND cr.reporting_year_id = 1 AND cr.date_retired IS NULL 
ORDER BY cr.category_id

1 个答案:

答案 0 :(得分:1)

这将变得如此丑陋。最好将response列添加到cr表格中的创建视图。

SELECT cr.category_id, cr.category_response_id,
    CASE 
    WHEN q.question_response_table = '...' THEN
        (SELECT response
         FROM ... r
         WHERE r.category_response_id = cr.category_response_id)
    ... 
    ELSE '' 
    END AS response
FROM category_responses AS cr 
JOIN response_key_questions AS rkq ON cr.category_id = rkq.category_id 
JOIN questions AS q ON q.question_id = rkq.question_id
WHERE cr.belongs_to = 4 AND cr.reporting_year_id = 1 AND cr.date_retired IS NULL 
ORDER BY cr.category_id