The way to organize SQL code

1. In work, when I see many people writing SQL code, it is a long string of characters that hits the world. It is difficult to see the structure and understand the meaning of the sentence. Today I will summarize a little bit of my habitual experience. If it is not comprehensive, I will treat it as an essay experience.

2. There are mainly three aspects:

1. Capitalize keywords and write them on a single line. This is mainly a suggestion. In order to see the structure of the sentence more clearly, if you feel that you can read lowercase, that's okay;

2. There must be indentation between different levels of statements; this makes it easy to see the inclusion relationship and statement debugging;

3. Try to use aliases and make aliases as meaningful as possible.

3. Examples:

SELECT
	tb.days,
	tb.tstep,
	tb.name,
	tb.sex,
	tb.birth,
	CASE
	  WHEN @rowtotal = sum(tb.tstep) THEN @rownum
	  WHEN @rowtotal := sum(tb.tstep) THEN @rownum :=@rownum + 1
	  WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1
	END AS rank
FROM
   	( 
       SELECT
		  DATE_FORMAT(rn.datetime,'%Y%m%d') days,
		  sum(rn.step) as tstep,
		  rn.uid as uid,
		  u.name,
		  u.sex,
		  u.birth
	   FROM
	      run as rn
	      LEFT JOIN users u on u.uid = rn.uid
	   WHERE
          rn.datetime >= ? and rn.datetime < ?
	   GROUP BY
		  days,uid
	   ORDER BY 
          tstep DESC
	   LIMIT 20
	) as tb,
	(SELECT 
       @rownum := 0 ,
       @rowtotal := NULL
    ) r

 

Guess you like

Origin blog.csdn.net/joyksk/article/details/100779383