【发布时间】:2013-05-06 02:09:52
【问题描述】:
使用所有表中存在的 id 来链接数据,从 3 个表中获取记录的最有效方法是什么?
第一个表:id 不是主键。许多记录具有相同的 id 值。该表的主键是“primary_id”
第二张表:id为主键
第三张表:id为主键
所以我们在“id”上有一个从第一个表到其他两个表的多对一关系。当然,第二到第三个表在“id”上具有一对一的关系,因为“id”是它们的主键。
我想从第一个表中选择 5 条记录(假设按第一个表排序 primary_id asc - 不是跨表共享 id)但我也想要其他两个表中的记录。
我应该得到
table1.primary_id | table1.id | table1.some_data | table2.some_data | table3.some_data
--------------------------------------------------------------------------------------
1 | 22 | oranges | fruit seller | company
4 | 22 | watermelons | fruit seller | company
13 | 22 | bananas | fruit seller | company
15 | 22 | pears | fruit seller | company
19 | 22 | beans | fruit seller | company
如你所见,在table2中,id为主键,id=22有some_data=fruit Seller,在table3中,id为主键,id=22有some_data=company
我应该使用什么来获取表 1 的 primary_id 的前 5 条记录,并像我演示的那样从其他两个表中获取记录?
加入?子查询?我担心的是性能。
【问题讨论】:
-
JOINs 通常性能更好。 -
你有
table1.id的索引吗? -
@MarkBannister 我可以创建任意数量的索引,因为插入很少见。是的,可以有一个索引。和任何其他索引。特别是我已经索引了 table1.id 列
标签: mysql select indexing query-performance