哪个有更好的性能,加入或子查询?

时间:2015-03-11 12:14:47

标签: mysql

我使用连接和子查询编写了一个查询,但我不知道哪个具有更好的性能。你能告诉我吗?

我的查询使用子查询:

SELECT e.e_id,e.name,e.email, (SELECT mc.m_id FROM table3 AS mc WHERE e.mobile = mc.c_mobile AND e.status=0 AND mc.currentdate<= e.currentdate LIMIT 1 ) AS cm_id
FROM table1 AS e
INNER JOIN table3 AS m
ON e.e_id = m.m_id AND m.m_status = 1
WHERE e.city LIKE 'wgl' AND e.status >= 0
GROUP BY e.email
ORDER BY e.status ASC, e.currentdate DESC

我的查询使用连接:

SELECT e.e_id,e.name,e.manager_id,mc.m_id AS cm_id
FROM table1 AS e
LEFT JOIN table3 AS mc
ON e.mobile = mc.c_mobile AND e.status=0 AND mc.currentdate <= e.currentdate
INNER JOIN table2 AS m
ON e.manager_id = m.m_id AND m.m_status = 1
WHERE e.city LIKE 'wgl' AND e.status >= 0
GROUP BY e.email
ORDER BY e.status ASC, e.currentdate DESC

哪个表现更好?我怎么知道哪个最好?

1 个答案:

答案 0 :(得分:0)

默认情况下,MySQL使用Block Nested-Loop连接算法进行连接。

SELECT t1.*, t2.col1
FROM table1 t1
LEFT JOIN table2 t2
  ON t2.id = t1.id

实际上,产生与子查询相同的性能,如下所示:

SELECT t1.*, (SELECT col1 FROM table2 t2 WHERE t2.id = t1.id)
FROM table1 t1

索引对于满足子查询中的WHERE子句显然很重要,并且以相同的方式用于连接操作。