【发布时间】:2016-09-20 06:56:06
【问题描述】:
我有两个独立的查询,它们具有相同的输出。现在我想了解哪个更好?
查询1:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|----|-------------|-------|------|---------------|--------|---------|--------|------|----------------------------------------------------|
| 1 | SIMPLE | t1 | ALL | (null) | (null) | (null) | (null) | 9 | Using where |
| 1 | SIMPLE | t2 | ALL | (null) | (null) | (null) | (null) | 9 | Using where; Using join buffer (Block Nested Loop) |
查询2:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
|----|--------------------|-------|------|---------------|--------|---------|--------|------|-------------|
| 1 | PRIMARY | t1 | ALL | (null) | (null) | (null) | (null) | 9 | Using where |
| 2 | DEPENDENT SUBQUERY | t2 | ALL | (null) | (null) | (null) | (null) | 9 | Using where |
那么哪个更好,为什么?
我读到了EXPLAIN here,但我还是不知道哪个参数很重要?或者哪个参数告诉我这样一个列需要索引,或者我的查询需要优化?
在上面这两个解释的结果中,除了select_type 和extra 之外,所有列都是相同的。那么哪个更好:
-
SIMPLE,SIMPLE -
PRIMARY,DEPENDENT SUBQUERY
-
-
Using where,Using where; Using join buffer (Block Nested Loop) -
Using where,Using where
-
编辑:这是这两个查询:
查询1:
SELECT t2.color FROM mytable t1
JOIN mytable t2 ON t1.related = t2.id
WHERE t1.id = '4'
查询2:
SELECT t1.color FROM mytable t1
WHERE exists (select 1 from mytable t2
where t1.id = t2.related
and t2.id ='4')
【问题讨论】:
-
您能否向我们展示这两个查询,假设它们可以合理地适合问题?您的两个查询的当前运行时间是多少?
-
创建一个大型测试数据集并运行两个查询器,看看哪个运行得更快。
-
@TimBiegeleisen 我已将这两个查询添加到我的问题中。
-
"或者哪个参数告诉我这样的列需要索引,或者我的查询需要优化?"解释中没有这样的列。如果解释告诉我们如何更改您的查询,那就太容易了。由您来解决这个问题,并解释是一个很好的工具来帮助解决这个问题。
-
@Shadow 是的,基准测试会有所帮助。但实际上我试图了解
EXPLAIN在这种情况下如何帮助我。
标签: mysql sql query-performance explain