mysql-sql practical scenarios/sql practical scenarios

 

1. Data type conversion

 MySQL string '123' is converted to number 123

Method 1: SELECT CAST('123' AS SIGNED);

Method 2: SELECT CONVERT('123',SIGNED);

Method 3: SELECT '123'+0;

 

2. Count the number of characters

 length(str1)-length(replace(str,'a',''))

 

3. Judging that the value starts with a number or letter

{String} REGEXP'[^0-9.]': If the String contains a number other than 0-9 or a decimal point, it returns true, otherwise it returns false.

For example:

select ('123a' REGEXP'[^0-9.]'); --'123a' contains the character'a' and the output result is 1 The constant true in mysql is output as 1 false and the output is 0

Note: If the string has spaces, it will also return 1. You can use the trim() function to remove the spaces at both ends.

(1) The filter does not start with a number

select * from mot_terms where `name` not REGEXP '^[0-9]' 

(2) Filtering does not start with a letter

select * from mot_terms where `name` not REGEXP '^[a-zA-Z]' 

(3) Filter the beginning of numbers and special characters

select * from mot_terms where `name` REGEXP '^[@#$%&0-9]' 

 

 4. Determine whether the field is Chinese

method one:

SELECT col FROM table WHERE length(col)!=char_length(col);

When the character set is UTF-8 and the character is Chinese, the results returned by the length() and char_length() methods are different.

Method Two:

SELECT name FROM user WHERE NOT (name REGEXP "[u0391-uFFE5]");

 

 

 

 

Guess you like

Origin blog.csdn.net/helunqu2017/article/details/113816045