MySQL - 根据 Key/Value 查找转换编码值 Table

MySQL - Convert coded values based on Key/Value Lookup Table

我有 2 个 MySQL table。一个包含表单条目,另一个包含要查找的 key/values 对。

它们的结构如下:

Table 1 : form_123

id | element_6 | element_7 | element_8 | element_9
1       1          6             3           6
2       4          7             2           4
3       3          3             5           2


Table 2 : Options

id   |  formid   |   option_id    |  option_name
1        123             1            sausages
2        123             2            bananas
3        123             3            grapes
4        123             4            fish
5        123             5            bread
6        123             6            buckfast
7        123             7            foo
8        123             8            bar
9        123             9            apples
10       123            10            oranges

什么是最优雅的MySQL 查询以提供以下输出。目的是在可能的情况下通过单个 select 语句将 table form_123 中的 key/value 查找代码转换为查找值。

id | element_6 | element_7 | element_8 | element_9
1   sausages      buckfast     grapes    buckfast
2       fish       foo         bananas   fish
3       grapes     grapes      bread     bananas

像这样使用 INNER JOIN

SELECT f.id,
       o6.option_name as element_6,
       o7.option_name as element_7,
       o8.option_name as element_8,
       o9.option_name as element_9
FROM form_123 f
INNER JOIN options o6 ON f.element_6 = o6.option_id
INNER JOIN options o7 ON f.element_7 = o7.option_id
INNER JOIN options o8 ON f.element_8 = o8.option_id
INNER JOIN options o9 ON f.element_9 = o9.option_id
ORDER BY f.id ASC

sqlfiddle 顺便说一下,您的示例所需输出似乎不对。

输出

id  element_6       element_7       element_8       element_9
1   sausages        buckfast        grapes          buckfast
2   fish            foo             bananas         fish
3   grapes          grapes          bread           bananas

如果你有更多的 formid(s) 你可以添加 WHERE all formids are 123 像这样

SELECT f.id,
       o6.option_name as element_6,
       o7.option_name as element_7,
       o8.option_name as element_8,
       o9.option_name as element_9
FROM form_123 f
INNER JOIN options o6 ON f.element_6 = o6.option_id 
INNER JOIN options o7 ON f.element_7 = o7.option_id 
INNER JOIN options o8 ON f.element_8 = o8.option_id 
INNER JOIN options o9 ON f.element_9 = o9.option_id 
WHERE o6.formid = 123
  AND o7.formid = 123
  AND o8.formid = 123
  AND o9.formid = 123
ORDER BY f.id ASC

或者您可以像这样在 ON 条件上添加 AND formid = 123 条件

SELECT f.id,
       o6.option_name as element_6,
       o7.option_name as element_7,
       o8.option_name as element_8,
       o9.option_name as element_9
FROM form_123 f
INNER JOIN options o6 ON f.element_6 = o6.option_id AND o6.formid = 123
INNER JOIN options o7 ON f.element_7 = o7.option_id AND o7.formid = 123
INNER JOIN options o8 ON f.element_8 = o8.option_id AND o8.formid = 123
INNER JOIN options o9 ON f.element_9 = o9.option_id AND o9.formid = 123
ORDER BY f.id ASC