当前位置:网站首页>MySQL learning notes (stage 1)

MySQL learning notes (stage 1)

2022-07-06 14:24:00 Lan Zhou Qianfan

use mysql;
create table if not exists stu2
(
	sid int(11),
	name varchar(10),
	gender varchar(10),
	brith date
	
);
show table stu1;
show columns from  stu1;
-- alter table stu2 add address varchar(10); 
alter table stu2 add (address varchar(10),score int(10));
insert into stu2 values(1," li "," male ","1000-12-12"," Beijing ",44),(2," Hua Tuo "," male ","1201-12-13"," three countries ",100);
select distinct * from stu2; # No duplicate record search 
select * from stu1 as p1; -- as  It can be omitted 
select *from stu2 as p2; --  names 
select name , score+10 score  from stu2;
select  distinct * from stu2 where name = " li ";  --  Conditions of the query 
select * from stu2 where not (name =" li ");

--  A query condition is nested 
-- if If the statement is satisfied, it returns yes, If you are not satisfied, return no
select a,b,c,
if(a*a=b*b+c*c or a*a+b*b=c*c or a*a+c*c = b*b,'Yes','No') as right_triangle
from line_segments;

select * from stu2 where score >=100;
# interval 
select * from stu2 where score between 40 and 101;
select * from stu2 where score >=40 and score <=100;
select * from stu2 where score >=40 && score<=101;
# or 
select * from stu2 where score in(50,100); -- 50or100
select * from stu2 where score =50 or score =100;
# Keyword query ···
select * from stu2 where name like "% Tuo "; --  Tuo end 
select * from stu2 where name like "% since %"; --  The word in the middle is from 
select * from stu2 where name like "_ since %"; --  The second word stands for self , Whatever's in the back 
#c see NULL
select * from stu2 where sid is null;
select * from stu2 where sid is not null;
# Check the minimum and maximum values 
select least(10,5,10) as small_number; --  If one of the numbers is null, It's directly NULL
select greatest(10,20,30) as big_number; --  The maximum is the same as above 
select * from stu2 order by score asc; --  according to score In ascending order ,asc It can be omitted . Order as  desc
select * from stu2 order by score desc , sid desc; --  First sort according to the first , Then if the first one is the same , Just sort according to the second .
--  Inquire about  name ,score  And in accordance with the score Arrange in descending order 
select  distinct name,score from stu2 order by  score desc; 
--  Number of queries ( Do not count lines that contain empty )
select count(*) from stu2;
select count(sid) from stu2;
select count(sid) from stu2 where score >50;
select sum(score) from stu2 where score = 100;
select  max(score) from stu2 where name = ' Hua Tuo ';
select min(score) from stu2 where name = ' Hua Tuo ';
select avg(score)from stu2 where name = ' Hua Tuo ';
use mysql;
create table product
(
	id bigint(20),-- 20 The number of digits representing the value 
	name varchar(10),
	price double,
	producer varchar(10)

);
insert into product values(1," Haier freezer ",3400,' haier '),(2,' Haier freezer ',4000,' haier '),(3,' Haier electric fan ',2400," haier ");
insert into product (id,name,price,producer) values (4," Gree air conditioning ",6000," gree "),(5,' Gree Electric fan ',1300," gree "),(6,' Lining sports shoes ',500,' Lining '),
(7,' Li Ning Wei Yi ',300,' Lining ');
--  Add or modify field properties 
alter table product modify price double(16,0) comment ' Price ';
alter table product alter price set default 200;
insert into product values(8,'oppoA11',2300,'oppo'),(9,'oppoA13',3000,'oppo');
--  Delete duplicate statistics 
--  Do not directly investigate the data as a condition of data deletion , We should start by creating a new temporary table with the data we find , The temporary table is then dropped as a condition 
--  Doing multi table query , Or this error occurs when a new table is generated during query :Every derived table must have its own alias( Each derived table must have its own alias ) Like the following a
delete from product where id in (select id from(select id from product group by id having count(id)>1)as a)
select  * from product order by id; --  The default in accordance with the id Arrange in descending order 
--  Grouping is usually put together with aggregation ,select Only the unique field can be selected as the standard .
select  producer,count(id) from product group by producer; 
--  Reorder the primary keys , Remove disorder 
alter table product drop column id;
alter table product add id int(4) not null primary key auto_increment first;
--  according to producer Grouping , Corresponding cnt(count(id) Get the number of aliases , And then according to cnt Sort the size of ( Default ascending order ))
select producer, count(id) cnt from product group by producer having cnt > 1 order by cnt;
-- limit n  Show the first few 
-- limit m,n  from m+1 Start , Show n strip 
select * from product limit 5; --  Show the first five 
select *from product limit 3,5;
use mysql;
select * from product;
create table produc2
(
	name varchar(20),
	price double(8,1)

);
alter table produc2 rename product2;
insert into product2(name,price) select name,price from product; --  Insert fields 
-- isnull(number)  Judge number Is it empty , If it is empty , return 1, Otherwise return to 0
-- ifnull(number1,number2), Judge number1 Is it empty , If it is empty, use number2 Instead of number1
-- nullif(number1,number2), If number=number, return null, Otherwise return to number1
--  Regular expressions 
-- ^ Match at the beginning of the string 
select  'abc' regexp '^a';
select * from product where name regexp "^ The sea ";
-- ^ Start matching at the end of the string 
select  'abc' regexp 'c$';
select * from product where name regexp ' Er $';
--  Match any character (. It can match any character except line feed ( Single character ))
select 'abc' regexp '.b';
-- [...] Match any character in brackets 
select 'abc'  regexp '[asn]'; #  Indicates whether any character in parentheses appears in the previous string , If yes , Just go back to 1
-- [^...]  Represents that any character does not appear , Contrary to the above  
-- a*  Represents a match 0 One or more a, Contains an empty string . Can be used as a placeholder , Whether the specified characters can match the data 
select 'stab' regexp 'ta*b'; -- a* Express a Can appear 0 Times or more 
-- a+   Represents a match 1 One or more a
select 'stab' regexp 'ta+b';
-- a? Represents a match 0 One or one character 
select 'stb' regexp '.ta?b';
-- a|a1  matching a perhaps a1
select 'a' regexp 'a|a1';
-- a{
    m}  appear m Time 
select 'annna' regexp 'an{3}a';
-- a{
    m,}, matching m One or more a
-- {
    m,n} At least m Time , most n Time 
--  Create department table 
create table if not exists dept
(
	detpno varchar(20) primary key, --  Department number 
  name varchar(20) --  Department name 
	

);
create table if not exists emp
(
	eid varchar(20) primary key, --  Employee number 
	ename varchar(20), --  Employee name 
	age int, --  Age of employee 
	dept_id varchar(20), --  The Department to which the employee belongs 
	constraint emp_fk foreign key (dept_id) references dept(detpno)
);
 --  When foreign key constraints exist directly in multiple tables , When deleting, you cannot delete the main table directly 
 --  Delete foreign key constraint 
 alter table emp drop foreign key emp_fk ;

select * from emp,dept;
--  Foreign key constraints have no effect on queries 
--  Cross join query 
select * from emp where age > all(select age from emp where dept_id = "1003");
select * from emp where age > all(60,58);
--  Query employee information that does not belong to any department 
select * from emp where dept_id != all(select detpno from dept);
-- any keyword (some  and  any  It does the same thing ), It can be understood as any 
select * from emp3 where age > any(select age from emp3 where dept = '1003') and dept_id!= '1003';
-- IN( Subquery keyword )
-- mysql  function 
-- group_concat, The data of one column is merged into one row 
select group_concat(name) as result from employee; --  The default result is between , Division of no. 
--  Set the interval symbol between query data 
select group_concat(name separator";")  as result from employee; 
--  Specify sorting method and separator 
select department,group_concat(emp_name separator ';') from emp group by department; --  Group first , You can think of grouping according to departments first , Then merge the names of the same department into one line 

--  You can also group , Merge the names into a row and then sort , Sort by salary 
select department,group_concat(emp_name order by salary separator ';')
from emp group by department; --  notes :group_concat Inside  separator  It has to be at the end 
--  Mathematical functions 
--  Take the absolute value 
select abs(-10);
select abs(10);
--  Rounding up 
select ceil(1.1); --  Returns the smallest integer larger than it 
select floor(1.1) --  Rounding down 
--  Returns the maximum value in the list 
select greatest(1,2,3);
--  Find the minimum value in the list 
select least(1,2,3);
--  Mod 
select mod(5,2);
--  take x Of y Power 
select power (2,3);
--  Take random number 
select rand() * 100; --  Generate 0 To 100 Random number of 
--  Take the rounding of decimals 
select round(3.1415);
--  Round to the specified number of decimal places 
select round(3.1415,3);
-- avg()  Average 
select category_id,avg(price) from product group by category_id;

--  Cut the decimal directly to the specified number of digits , No rounding occurs 
select truncate(3.1415,3);

--  String function 
-- char_length()  function , Find the number of characters in the string 
select char_length("jgdabc");
-- length()  Take the length , Return byte 
select length(" Hello ");
-- concat()  Merge strings 、
select concat('hello','world');
--  Specify the separator when merging 
select concat_ws('-','hello','world')
--  Returns the first position of the string in the list 
select field('aaa','aaa','bbb','ccc'); --  What you are looking for is the first parameter 
-- ltrim() Remove the space to the left of the string 
select ltrim(' aaaa');
-- rtrim()  Remove the space to the right of the string 
select rtrim('sask ');
-- trim()  Remove the spaces at both ends 
select trim(" sjsn ");
-- mid()  Intercepting string 
select mid("helloworld",2,3); --  Intercept from the second character , Intercept three , The intercept length is three 
-- position(a in b) Get string a stay b Where in 
select position("abc"in"abcsk");
-- replace(str1,str2,str3) String substitution , The string str1 Medium str2 Replace with str3
select replace("hello world",'hello','hi');
-- reverse()  String inversion 
select reverse("hello");
-- right()  Returns the last few characters of a string 
select right("Hello",3
-- strcmp(), String comparison 
select strcmp("hello","Hello");
-- substr()  String interception 
select substr("hello",2,3);
-- substring()  String interception , Same as above 
-- ucase(),upper() Convert lowercase to uppercase 
select ucase("Hello world");
select upper("Hello World");
-- lcase(),lower()  Change upper case to lower case 
select lcase("HELLO");
select lower("WORLD");

-- 
 --  Date function 
 
 select UNIX_TIMESTAMP(); --  Get the timestamp ( Millisecond value )  from  1970 year 
--  Convert a date string to a millisecond value 
select UNIX_TIMESTAMP('2021-12-21 08:00:00'); -- Or from the 1970 Year begins 
--  Converts the timestamp to the specified format · date 
select FROM_UNIXTIME(1924023030,'%Y-%m-%d %H:%i:%s')
--  Get the current date 
select curdate()
select current_date();
--  Get the current hour, minute, second 
select current_time();
select curtime();
--  Get the current time and date 
select current_timestamp() 
--  Get the date from the date string 
select date('2022-12-12 12:34:56')
--  Gets the difference between dates 
select datediff("2021-12-23","2008-08-08");
--  Get the difference in seconds 
select timediff('12:12:34','10:18:56');
--  Convert the date in the specified format ( Date formatting )
select date_format('2021-1-1 1:1:1','%Y-%m-%d %H:%i:%s');
--  Convert string to date 
select str_to_date('2021-1-1 1:1:1','%Y-%m-%d %H:%i:%s');
--  Subtract the date 
select date_sub('2021-10-01',interval 2 day);
select date_sub('2021-10-01',interval 2 month)

--  Add the date 
select date_add('2021-10-01',interval 2 day)
--  Get the specified value from the date 
select extract(hour from '2020-1-10 11:11:11');
--  Returns the last day of a given date 
select last_day('2021-08-11');
--  Gets the date of the year and the specified number of days 
select makedate('2021',53); --  obtain 2021 In the first 53 God 
--  Get Quarterly 
select quarter('2021-12-13 11:12:13');
--  Get the English name of the month and so on --
select monthname('2020-12-13 11:11;11');
select dayname('2020-12-13 11:11;11'); --  Get the day of the week ( english )
select dayofmonth('2020-12-13 11:11;11') --  Get the day of the month 
select dayofweek('2020-12-13 11:11;11'); --  Digital state 
select dayofyear('2020-12-13 11:11;11'); --  Get the day of the year 
--  Get the first few weeks of the year 
select week('2020-12-13 11:11;11');
select now(); --  Get the current time 
原网站

版权声明
本文为[Lan Zhou Qianfan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131401188355.html