我有一个数据库,其中一个表中的列是我需要在其中查找相应记录的表名。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 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
中的每个值列是另一个保存用户响应的表(原始数据库设计要求将响应按数据类型分隔到单独的表中)。
我有一个查询,除了用户的响应之外,它还提供了我需要的一切。但出于性能原因,我真的很想将该响应附加到同一查询上(数据库每年都会显着增长)。这是我想做的事情的一个例子:
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
最佳答案
这会变得很丑陋。最好创建一个 View ,将 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
关于mysql - 在 MySQL 查询中使用列名作为表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815070/