我有2个MySQL表。一个包含表单条目,另一个包含要查找的键/值对。
他们的结构如下:
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语句将表form_123中的键/值查找代码转换为查找值。
id | element_6 | element_7 | element_8 | element_9
1 sausages buckfast grapes buckfast
2 fish foo bananas fish
3 grapes grapes bread bananas
答案 0 :(得分:2)
像这样使用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 您的样品所需的输出似乎是关闭btw。
输出
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,你可以添加WHERE所有的格式都是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