读书人

关于数据库查询的 效率解决思路

发布时间: 2013-11-20 12:46:02 作者: rapoo

关于数据库查询的 效率
现在有这么一个需求, 在数据库中有12张表, 那12张表都是 信息, 但是每张表的信息 是不同的, 有共同字段,(mysql 数据库)

现在 用 union all 连接12张 表进行查询, 效率很慢 10W 条数据 SELECT COUNT(*) 用时 都是7s 时间, 请问 有什么好的 查询方法,
[解决办法]
select count(主键)
[解决办法]
在检索字段上建立索引
[解决办法]
建立索引吧,查询大数据不建索引不是找死。。。



引用:
Quote: 引用:

select count(主键)
我测试了下, count(primary key) 时间反而增加了

count(1)呢?试试
[解决办法]
引用:
Quote: 引用:

select count(主键)
我测试了下, count(primary key) 时间反而增加了


COUNT(1)和COUNT(*)是一样的,你可以在里面写任何常量,如COUNT('CSDNDSB'),不会输出一列常量,不会去系统表里找所有列名。
COUNT(1)和COUNT(列名)意义不同,不能放在一起比较。唯一可比较的情况是列名是单主键表的主键列,即聚集非空单键值索引,这种情况下除非想要强制走聚集索引扫描,否则COUNT(1)优于COUNT(列名),因为前者允许计划选择最估索引,而且没有列输出。

http://bbs.csdn.net/topics/390635419
[解决办法]
这个应该算比较开放的,推荐讨论下。
[解决办法]
ctrl + L 看下查询计划,你就知道瓶颈在哪里了,然后有针对性的去优化
[解决办法]
设计上不能再改改?
我是说数据库结构
[解决办法]
引用:
select * from (
select id from table1
union all
select id from table2
union all
select id from table3
union all
select id from table4
union all
select id from table5
union all
select id from table6
union all
select id from table7

) as temp WHERE xx= xx;


我这样查询是不是本身就是不正确的?


是有点问题,你这个union 7个表,尽量让每个子查询走索引,应该会快些,可以看看执行计划, 瓶颈应该在每个子查询上,union all 本身不耗什么时间的
[解决办法]
引用:
select * from (
select id from table1
union all
select id from table2
union all
select id from table3
union all
select id from table4
union all
select id from table5
union all
select id from table6
union all
select id from table7

) as temp WHERE xx= xx;


我这样查询是不是本身就是不正确的?


改为先筛选后联合应该会快点吧?另外过滤条件比较固定的话,在涉及到的列上加个索引应该也是个好方法。

select * from (
select id from table1 WHERE xx= xx;
union all
select id from table2 WHERE xx= xx;
union all
select id from table3 WHERE xx= xx;
union all
select id from table4 WHERE xx= xx;
union all
select id from table5 WHERE xx= xx;
union all
select id from table6 WHERE xx= xx;
union all
select id from table7 WHERE xx= xx;
)
[解决办法]
select 1 from bean
[解决办法]
select count(1) from bean

读书人网 >J2EE开发

热点推荐