【问题标题】:Best approach of mysql query: Get records from multiple tables, using an idmysql查询的最佳方法:使用id从多个表中获取记录
【发布时间】: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


【解决方案1】:

试试:

select t1.primary_id, t1.id, t1.some_data, t2.some_data, t3.some_data
from table2 t2
join table3 t3 on t2.id = t3.id
cross join (select * from table1 where id = 22 order by primary_id limit 5) t1
where t2.id = 22

确保table1.id上有索引;如果 id、primary_id 上有索引(按此顺序),则查询可能执行得更好。

【讨论】:

  • 感谢您的帮助,我正在创建一些测试数据并进行测试
猜你喜欢
  • 1970-01-01
  • 2017-01-19
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2022-08-04
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多