Advanced MySQL usage

1. Sort by Chinese Pinyin:

The Chinese in the table is utf8 encoding, first converted to gbk.

select name from table_name order by convert(name using gbk) asc

2. Multi-line to multi-column:

References: http://www.cnblogs.com/small8/p/6211009.html

For example, the field to be transferred from row to column is subject (subject), and the field to be assigned is score (grade), which can be converted as follows:

select  name,

MAX(CASE subject when 'Chinese' THEN score ELSE 0 END) 'Chinese',

           MAX (CASE subject when ' Math ' THEN score  ELSE 0 END) 'Math',

           MAX (CASE subject when ' English ' THEN score  ELSE 0 END) 'English'
from exam_result
group by name

3. The serial number in the group

Question: Suppose the fields of table table_1 are group_name, log_time, field_name1, field_name2. The requirement is to get the record with the smallest log_time in each group_name.

Implementation method: use a variable to record the value of the last grouping, if it is the same, count +1, otherwise count again

The SQL is as follows:

select group_name,log_time,field_name1

from

(

select group_name,log_time,field_name1, 

(@index:=CASE WHEN @last_group_name=group_name THEN @index+1 ELSE 1 END) record_index,(@last_group_name=group_name) last_group_name 

from 

(

select * 

from table_1 

order by group_name,log_time

)A,

(

select @index:=1,@last_group_name=''

)B

)C where record_index=1

4. Generate the sequence

Reference: http://yuanding.us/miscellany/4806/

For example to generate a sequence of dates for the last week:

select sequence_date
from 
(
select subdate(curdate(),t.i) sequence_date
from 
(
select 1 i union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 10 union select 11 union select 12 union select 13 union select 14
)t
)date_list
where yearweek(sequence_date,1)=yearweek(DATE_SUB(now(),INTERVAL 7 DAY),1) 
order by sequence_date

Note: The place to judge the date of last week is written as follows so that there will be no BUG for the new year:

yearweek(sequence_date,1)=yearweek(DATE_SUB(now(),INTERVAL 7 DAY),1) 

5. Take substring by delimiter

For example, the raw string format is as follows:

1.2.3.456

The goal is to take out 1.2.3

Implementation: substring_index('2.3.0.456','.',3)

6. Splicing of multiple select results:

select  * from a

union select * from b

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325951333&siteId=291194637