Performance exploration of MySQL case when and if

Scenes:

好奇心驱使的探索,实验结果可能并不严谨

Control variable method: In the same MySQL5.7 environment, the handwritten grouping continuous ranking function, the first group uses case when, and the second group uses if to rank 140,000 data and check the efficiency. The code is as follows.


code part

Ranking function (CASE WHEN mode):

SELECT
	CASE
	WHEN @pre_name = t.name THEN
		@cur_rank := @cur_rank + 1
	ELSE
		@cur_rank := 1
	END AS rank,
	@pre_name := t.name AS studentName,
	t.create_time
FROM
	student_score t,
	(SELECT @pre_name := NULL, @cur_rank := 0) r
ORDER studentNameY t.name ASC, t.create_time DESC

Ranking function (IF method):

SELECT
	IF(@pre_name = t.name, @cur_rank := @cur_rank + 1, @cur_rank := 1) AS rank,
	@pre_name := t.name AS studentName,
	t.create_time
FROM
	student_score t,
	(SELECT @pre_name := NULL, @cur_rank := 0) r
ORDER studentNameY t.name ASC, t.create_time DESC

Query speed:

In the case when mode, the execution speed is stable between 0.27s-0.29s. As shown in the figure:
insert image description here
In the if mode, the execution speed is stable between 0.42s-0.48s. As shown in the picture:
insert image description here


Summarize:

数据量较大情况下,CASE WHEN 的效率更高,IF效率略低一些.
The performance improvement of 0.2s may not be very big, but it can give users a better experience if you gather less to make more.

Guess you like

Origin blog.csdn.net/Fan_1504251998/article/details/127783724