我们有一个主表和一个辅助表来保存一堆与主表关联的键值对。这背后的原因是,随着我们数据的增长,不同类型“键”的数量也会增加。当前结构:
Main Table:
id|name
Secondary Table:
id|key|value
我想从主表中选择所有记录,并从辅助表中选择一些键。我现在的做法是:
SELECT main_table.id, main_table.name, s1.value, s2.value
FROM main_table
LEFT JOIN secondary_table s1 ON s1.id = main_table.id AND s1.key = 'cats'
LEFT JOIN secondary_table s2 ON s2.id = main_table.id AND s2.key = 'dogs'
我必须使用 LEFT JOIN,因为有些记录在第二个表中没有对应的记录,但无论如何我需要记录返回。这对我来说似乎效率低下而且速度很慢。也许我走错了路?如何改进结构/查询?