这两个SQL语句返回相同的结果,但第一个比第二个慢得多:
SELECT leading.email, kstatus.name, contacts.status
FROM clients
JOIN clients_leading ON clients.id_client = clients_leading.id_client
JOIN leading ON clients_leading.id_leading = leading.id_leading
JOIN contacts ON contacts.id_k_p = clients_leading.id_group
JOIN kstatus on contacts.status = kstatus.id_kstatus
WHERE (clients.email = 'some_email' OR clients.email1 = 'some_email')
ORDER BY contacts.date DESC;
SELECT leading.email, kstatus.name, contacts.status
FROM (
SELECT *
FROM clients
WHERE (clients.email = 'some_email' OR clients.email1 = 'some_email')
)
AS clients
JOIN clients_leading ON clients.id_client = clients_leading.id_client
JOIN leading ON clients_leading.id_leading = leading.id_leading
JOIN contacts ON contacts.id_k_p = clients_leading.id_group
JOIN kstatus on contacts.status = kstatus.id_kstatus
ORDER BY contacts.date DESC;
但我想知道为什么会这样?看起来在firt语句中首先完成连接然后应用WHERE子句,而第二个恰好相反。但它在所有数据库引擎上的行为方式是否相同(我在MySQL上测试过它)?
我期待数据库引擎可以优化查询,例如fors one和firs应用WHERE子句然后进行连接。
答案 0 :(得分:2)
这可能有很多不同的原因(键控等),但您可以查看explain mysql命令以查看语句的执行方式。如果你可以运行它,如果它仍然是一个神秘的帖子。
答案 1 :(得分:0)
你总是可以用嵌套查询替换连接...它总是更快但很麻烦......