1
wmttom Aug 19, 2015
你的写法是 cross join 相当于两个表做了笛卡尔积,根据情况改用 inner join 应该会快很多
|
2
heat OP |
4
mhycy Aug 19, 2015
SELECT count (*) FROM table_1
JOIN table_2 ON table_2.user='b' AND table_1.tid = table_2.id WHERE table_1.type='text' 试试? |
5
heat OP @mhycy 执行了 2.19 秒和我写的那段效率基本没差...
Explain 的结果如下 1 SIMPLE 表 1 ALL tid,type NULL NULL NULL 114299 Using where 1 SIMPLE 表 2 eq_ref PRIMARY PRIMARY 4 user.表 1.tid 1 Using where |
6
skydiver Aug 19, 2015
你的 table2 没建索引。
|
8
pubby Aug 19, 2015
先表 2 ,再 left join 表 1
select count (*) from t2 left join t2 on t2.id=t1.tid and t1.type='text' where t2.user='b' and t1.tid IS NOT NULL |
9
skydiver Aug 19, 2015
@heat 因为你先表 1 然后 join 表 2 ,这样只能用上 2 的索引,然后 2 还没索引。
所以要么 2 加上索引,要么拿 2 做驱动表, join 表 1 |
13
gamexg Aug 19, 2015 via Android
|
14
gamexg Aug 19, 2015
刚刚手机回复。
请确认 表 2.user 有索引。 猜测表 2 是用户表,应该优先使用 表 2.user 的索引 获得用户 id ,然后再根据用户 id 查询用户相关的帖子。 如果 表 2.user 没有索引,那么 mysql 只能先将 表 1.type='text' 的记录全部找出来,然后每个记录都去查询一下 表 2 ,速度绝对慢啊。 |
15
fwings260 Aug 19, 2015
SQL 不断句,不换行。。。看的蛋疼。。。
|
16
pubby Aug 19, 2015
explain 表 2 left join 表 1 那个查询 ,贴上来看看
|