MySQL联表查询的索引使用

MySQL联表查询的索引使用,第1张

一共3张表 knowledge , knowledge_question , knowledge_answer ,数据在 6000~10000 之间。 执行的语句: 执行时间约 10分钟 ,查看执行计划如下: 全部都是全表扫描,根据MySQL联表查询的算法 Nested-Loop Join ,MySQL查询的结果集是3张表的笛卡尔积,所以效率特别低。 耗时变成 20毫秒给Where条件建立索引,并不一定会使用。 比如:在表 knowledge 的字段 update 上建立索引 idx_time : 结果执行上来看,并没有使用索引 idx_time 。 如果where条件从 k.update_time>'2019-01-03 12:00:00' 修改为 k.update_time='2019-01-03 12:00:00' (从 >变成 = ) 则会使用索引 idx_time在建立索引的时候,会遇到 Table Metadata Lock 的问题,可以先 show processlist ,找到占用表锁的连接,然后 kill 。

create table node_tree( id int not null auto_increment primary key, node_name varchar(128) not null default '', up_node_id int, node_level char(1) )ENGINE=InnoDB default charset=utf8 collate=utf8_swedish_ci

insert into node_tree(node_name,up_node_id,node_level) values('jx',null,'1'),('jx.webserver',1,'2'),('jx.webserver.nginx1', 2, '3'), ('jx.logserver', 1, '2')

select

node_tree1.id as 主表ID,

node_tree1.name as 主表名字,

node_tree2.name as 从表名字,

node_tree2.up_id as 从表上级ID

from node_tree1, node_tree2

where node_tree1.name='jx'

select

node_tree1.id as 主表ID,

node_tree1.node_name as 主表名字,

node_tree2.node_name as 从表名字,

node_tree2.up_node_id as 从表上级ID

from node_tree as node_tree1, node_tree as node_tree2

where node_tree1.node_name='jx'

方法和 *** 作步骤如下:

1、首先,创建一个测试表,如下图所示,然后进入下一步。

2、其次,插入测试数据,如下图所示,然后进入下一步。

3、接着,完成上述步骤后,查询表中的数据,“select t.* from test_tbl2 t ”,如下图所示,然后进入下一步。

4、最后,完成上述步骤后,编写sql,两个表通过pid与id关联, “select t1.*, t2.* from test_tbl1 t1 join test_tbl2 t2 on t1.p_id = t2.id”,如下图所示。这样,问题就解决了。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/7257515.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-03
下一篇2023-04-03

发表评论

登录后才能评论

评论列表(0条)

    保存