询问一条sql语句的优化
大家好,我是一位新手,最近遇到一条sql语句,执行效率很慢,希望大家能帮忙优化下。
table `picture` (
`id` int(11) unsigned NOT NULL auto_increment,
`picture_desc` text NOT NULL,
`picture_rating` tinyint(1) NOT NULL default '1',
PRIMARY KEY (`id`),
)
table `pictag` (
`id` int(11) unsigned NOT NULL auto_increment,
`tag_des` text NOT NULL,
PRIMARY KEY (`id`),
)
table `picture_pictag` (
`id` int(11) unsigned NOT NULL auto_increment,
`picture_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `picture_id` (`picture_id`,`tag_id`),
KEY `pid` (`picture_id`),
KEY `tid` (`tag_id`)
)
picture是图片表、pictag是标签表、picture_pictag是关联表。(many_to_many关联)
现在picture表的数据约为20W条,pictag表的数据约为10W条,关联表picture_pictag的数据约为120W条。
现在我需要通过标签去查询图片,查询属于一部分标签,且不属于另一部分标签的图片。另外图片有一个picture_rating字段,要求picture_rating=1。
我写的查询语句如下:
select a.picture_id as picture_id from
( select c.`picture_id` from `picture_pictag` as c,
`picture_options` as d
where c.tag_id in (361,368,409,367,415,410)
and c.picture_id=d.id
and d.picture_rating=1
group by c.`picture_id` having count(c.`picture_id`)=6 ) a
left join `picture_pictag` b
on a.picture_id=b.picture_id
and b.tag_id in (772,7,80)
where b.picture_id is null
执行上面的查询,执行时间为1.672s
------解决方案--------------------
这个顺序涉及到索引结构,索引也是讲究顺序的。
USING BTREE是说他试用BTREE索引结构来seek。
如果数据更新频率快,查询效率还行的话,执行次数不多的,我觉得没有必要再建个临时表来维护,0.几秒算可以介绍吧,呵呵