Home > Database > Mysql Tutorial > body text

mysql 优化 left join

WBOY
Release: 2016-06-06 09:36:14
Original
1221 people have browsed it

mysql优化

A(id,name,createtime)
B(id,aid,name,createtime)
b是a的记录表,a保留一条最新的记录,历史的移动到b中,因此一条a在b中有多条历史记录;
需求:当a在b中有记录时,则时间取b中对应记录的最早的创建时间,其他字段取a中的。
如果b中无数据,则取a中的全部数据

现在的解决方案是(由于数据敏感,以下为原数据表结构的对呀模型):
-- 如果b中有记录:
SELECT * FROM (
SELECT A.id,A.name,B.createtime
FROM A
INNER JOIN B ON A.id=B.aid
ORDER BY B.createtime) tt
GROUP BY tt.id
UNION
-- 如果b中无记录http://ask.csdn.net/questions?type=reward#
SELECT A.*
FROM A LEFT JOIN B ON A.id=B.aid
WHERE B.id IS NULL

但是这样数据量过10万级别时候特别慢,A,B表都有主键。
求优化

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!