[英]Conditions in WHERE clause and in ON clause
Assume I have two tables, 假设我有两个表,
Student Test
Id Name TestId Type StudentId
-- ---- ------ ---- ---------
1 Mark 774 Hard 1
2 Sam 774 Hard 2
3 John 775 Easy 3
Now I have to find those students(the student id,name and testid) who have taken "hard" type of test in MySql. 现在,我必须找到在MySql中接受了“硬”类型测试的那些学生(学生ID,姓名和TestID)。
Which one is better(In terms of performance)?. 哪个更好(就性能而言)?
1.Select student.id,student.name,test.testid
from student
join test
on test.studentid=student.id and test.type='hard'
2.Select student.id,student.name,test.testid
from student
join test
on test.studentid=student.id
where test.type='hard'
May I know the reason? 我可以知道原因吗? (Assume there are millions of students and million types of tests)
(假设有数以百万计的学生和数百万种测试类型)
Both are same but with different performance . 两者相同,但性能不同 。 I recommend to you use
EXPLAIN PLAN
for queries if you want to choose query with better performance . 如果您想选择性能更好的查询,建议您使用
EXPLAIN PLAN
进行查询。
Have look at Understanding the Query Execution Plan . 看一下了解查询执行计划 。
Also you can improve your queries with INDEXES
for columns which you are using the most frequently in WHERE
clause, you can have look at relational algebra also. 另外,您可以使用
INDEXES
改进对WHERE
子句中使用频率最高的列的查询,也可以查看关系代数。
Those queries are exactly the same and should have exactly the same query plan. 这些查询完全相同,并且应该具有完全相同的查询计划。 It is unlikely that there will be any measurable difference in execution time.
执行时间不可能有任何可测量的差异。
There will however be a difference if you change JOIN
to LEFT JOIN
. 但是,如果将
JOIN
更改为LEFT JOIN
将会有所不同。 In that case you need to use the first version. 在这种情况下,您需要使用第一个版本。 The second version will not give the same results.
第二个版本不会给出相同的结果。
Performance-wise these two are about the same. 在性能方面,这两者大致相同。 You can verify that by using the EXPLAIN command.
您可以使用EXPLAIN命令来验证。
So the question becomes one of clarity of expression of your data model. 因此,问题变成了数据模型表达的清晰性之一。 It may seem like angels dancing on the head of a pin.
好像天使在别针上跳舞。 But, if you're pulling all the test results with your JOIN commmand, and then asking for a subset, go with
WHERE type='hard'
. 但是,如果要使用JOIN命令提取所有测试结果,然后要求一个子集,请使用
WHERE type='hard'
。
But if, conceptually, you're pulling only the hard ones, then go with the ON
formulation. 但是,如果从概念上讲,您只是在艰难地解决问题,那么就采用
ON
公式。
Notice that these two will work differently if you use LEFT JOIN
. 请注意,如果您使用
LEFT JOIN
,则这两个将以不同的方式工作。 You'll get a row for each student that hasn't ever taken a hard test, as well as a row for each hard test each student has taken if you use the ON
formulation with LEFT JOIN
. 如果您将
ON
公式与LEFT JOIN
一起使用,您将为没有经过硬测试的每个学生排一次,以及为每个学生进行的每个硬测试排一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.