Home  >  Article  >  Database  >  mysql 优化 left join

mysql 优化 left join

WBOY
WBOYOriginal
2016-06-06 09:36:141222browse

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表都有主键。
求优化

Statement:
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