MySQL packets and even table query

MySQL packets and even table query

2019-08-23

1.MySQL grouping

Attribute in accordance with one drop data packets, by keywords: group by; packet will normally be used in combination with a polymerization function.

Aggregate functions are used: min, max, sum, avg, count.

Statistics such as the number of male and female students

--性别表
create table gendertable(
    id int auto_increment primary key,
    gender char(10)
)engine=innodb default charset=utf8;

insert into gendertable(gender) values("男"),("女");

--人员表
create table personnel(
    id int auto_increment primary key,
    name char(10),
    gender int not null,
    constraint fk_per_gend foreign key gender references gendertable(id)
    )engine=innodb default charset=utf8;

select count(gender),max(id),gender from personnel group by gender;

Note here that, when the results of the secondary screening aggregate functions can not be used where, but the use of having.

The following are the statistics display, the number of statistical data is greater than a certain gender 2

select count(gender),gender from personnel group by gender having count(gender)>2;

Query a table in a total of how much data you can use the following method:

select count(1) from 表名;

2. Double-table query

The two or more tables in the query together;

There must be a mapping relationship between the tables;

Syntax: Keywords on followed by mapping relationships between tables

select the column or content to be displayed from Table. 1 left  the Join 2 tables on the relation between Tables 1 and 2;

left join its left will display the whole table.

Can also be achieved even more than one table table, at least as long as there is an association between two tables

select required display contents from Table. 1
 left  the Join Table 2 ON relationships between tables
 left  the Join Table. 3 ON relationships between tables 
?????

Example:

- status table 
Create  Table Status ( 
    ID int  Not  null AUTO_INCREMENT Primary  Key , 
    STA char ( 10 ) Not  null 
    ) Engine = InnoDB default charset = UTF8; 

INSERT  INTO Status (STA) values ( "excited"), ( "happy") , ( "calm"), ( "low");

create table userinfo(
    id int not null auto_increment primary key,
    name char(10) not null,
    sta_id int not null,
    constraint fk_usr_sta foreign key (sta_id) references status(id)
    )engine=innodb default charset=utf8;
insert into userinfo(name,sta_id) values("mok",3),("cag",1),("sohh",2),("kaly",4),("doom",3),("jugg",1),("tiger",4),("lion",4);

#连表查询
select name,sta from userinfo
left join status on userinfo.sta_id=status.id;

 

Guess you like

Origin www.cnblogs.com/sienbo/p/11398017.html