sql 效率问题

WBOY
Release: 2016-06-06 20:42:21
Original
1067 people have browsed it

有这样一个疑问,如果是一系列比较复杂的操作,跨表、累加之类的,简单的 sql 可能需要执行两个以上才能完成。

用编程语言多次执行,结果集里面折腾有效率呢;还是想尽办法写个高深的 sql,一次解决问题呢?

俺 sql 很水,编程语言也只是中下游水平,又有一颗追求优雅、高效之心。

举个例子:

有个临时表,存储 pid, tid, duration,通过一次 select,将 (pid, tid) 作为唯一组合,统计其出现次数(count),和 duration 累加总和。
然后将 pid, tid, count, duration 存入另外一个表,还要保证另外一个表的 (pid, tid) 是唯一组合。

插入部分的唯一性已经写出了稍微复杂的 sql,现在在考虑是将第一部分的结果集遍历再分别插入,还是再考虑一个更复杂的 sql。

ps: 第二部分插入的题目在:http://segmentfault.com/q/1010000000723454
所用的 sql 为:

<code>alter table stat add unique index pid_and_tid (pid, tid);

insert into stat (pid, tid, count, duration)
    values (1, 1, 1, 1)
    on duplicate key update
    count = count + 1, duration = duration + 1
</code>
Copy after login
Copy after login

回复内容:

有这样一个疑问,如果是一系列比较复杂的操作,跨表、累加之类的,简单的 sql 可能需要执行两个以上才能完成。

用编程语言多次执行,结果集里面折腾有效率呢;还是想尽办法写个高深的 sql,一次解决问题呢?

俺 sql 很水,编程语言也只是中下游水平,又有一颗追求优雅、高效之心。

举个例子:

有个临时表,存储 pid, tid, duration,通过一次 select,将 (pid, tid) 作为唯一组合,统计其出现次数(count),和 duration 累加总和。
然后将 pid, tid, count, duration 存入另外一个表,还要保证另外一个表的 (pid, tid) 是唯一组合。

插入部分的唯一性已经写出了稍微复杂的 sql,现在在考虑是将第一部分的结果集遍历再分别插入,还是再考虑一个更复杂的 sql。

ps: 第二部分插入的题目在:http://segmentfault.com/q/1010000000723454
所用的 sql 为:

<code>alter table stat add unique index pid_and_tid (pid, tid);

insert into stat (pid, tid, count, duration)
    values (1, 1, 1, 1)
    on duplicate key update
    count = count + 1, duration = duration + 1
</code>
Copy after login
Copy after login

几乎任何时候降低数据库的 计算复杂度 都是好的。

内存可重复利用,容易扩展,在大多数场景下都可以利用内存来换取数据库性能,即:从数据库中简单地取出数据,再在内存中处理成想要的数据。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!