日期:2014-05-16  浏览次数:20667 次

求一条sql语句,需要效率
以下字段全为varchar
Table   A   (bid,cid必有一个为空)
------------------------
time    
bid        
cid


Table   B
------------------------
bid
bname
type


Table   C
----------------
cid
cname
type


Table   type
---------------------
type
name1
name2

需要得到这样的结果
time         bid         bname         cid         cname
但是需要对name1和name2加限制

我是这样做的
select   a.time,   a.bid,   b.name,   a.cid,   c.name  
from   A   a,   B   b,   C   c,   Type,   t
where   a.bid   =   b.id  
        and   a.cid   =   c.id  
        and   (b.type   =   t.type   or   (a.bid= ' '   and   c.type   =   t.type))
可是这条sql在10万条记录的A表上(我还有几个表连接(这几个连接同A与B之间关系相同,应该不是它们的问题),居然执行了150多秒
请高手指点

------解决方案--------------------
不知道为什么所有的字段都要 varchar ,为什么不使用 int 或者 char?

------解决方案--------------------
1.有索引就一定要用索引(注意顺序)
2.注意关联的顺序
select a.time, from A a, B b where a.bid = b.id

select a.time, from A a, B b where b.bid = a.id
的效率是不一样的.
尤其是当A,B表大小相差很大时.
一般是小表放在 "= "右侧
------解决方案--------------------
hehe ,不知道最后执行的时间是?
如果有主键,mysql会自动去取主键的,这个比索引的效率要好。
否则,就去取索引,如果都没有,那么mysql只有执行最傻的操作了:全表搜索。

取主键和索引都可以直接定位,但是主键更快一些。这么说,楼主明白了吗?
------解决方案--------------------
学习了