Home Database Mysql Tutorial Enhanced version of sql statements that you must know about MySQl database

Enhanced version of sql statements that you must know about MySQl database

Apr 18, 2017 am 09:22 AM

This article shares with you an article about the enhanced version of mysqlThe database must know the sql statement. It is very good and has reference value. Friends who need it can refer to it

This article is an enhanced version. The questions and SQL statements are as follows.

Create users table, set id, name, gender, sal fields, where id is the primary key

drop table if exists users; 
create table if not exists users( 
  id int(5) primary key auto_increment, 
  name varchar(10) unique not null,   
  gender varchar(1) not null, 
  sal int(5) not null 
); 
insert into users(name,gender,sal) values('AA','男',1000); 
insert into users(name,gender,sal) values('BB','女',1200);
Copy after login

------------------- -------------------------------------------------- ------------------

One-to-one: What is AA’s identity number

drop table if exists users; 
create table if not exists users( 
  id int(5) primary key auto_increment, 
  name varchar(10) unique not null,   
  gender varchar(1) not null, 
  sal int(5) not null 
); 
insert into users(name,gender,sal) values('AA','男',1000); 
insert into users(name,gender,sal) values('BB','女',1200); 
drop table if exists cards; 
create table if not exists cards( 
  id int(5) primary key auto_increment, 
  num int(3) not null unique, 
  loc varchar(10) not null, 
  uid int(5) not null unique, 
  constraint uid_fk foreign key(uid) references users(id) 
); 
insert into cards(num,loc,uid) values(111,'北京',1); 
insert into cards(num,loc,uid) values(222,'上海',2);
Copy after login

[Note: inner join means within Connection]

select u.name "姓名",c.num "身份证号" 
from users u inner join cards c 
on u.id = c.uid 
where u.name = 'AA'; 
-- 
select u.name "姓名",c.num "身份证号" 
from users u inner join cards c 
on u.id = c.uid 
where name = 'AA';
Copy after login

---------------------------------------- -------

One-to-many: Query Which employees are in the "Development Department"

Create groups table

drop table if exists groups; 
create table if not exists groups( 
  id int(5) primary key auto_increment, 
  name varchar(10) not null 
); 
insert into groups(name) values('开发部'); 
insert into groups(name) values('销售部');
Copy after login

Create emps table

drop table if exists emps; 
create table if not exists emps( 
  id int(5) primary key auto_increment, 
  name varchar(10) not null, 
  gid int(5) not null, 
  constraint gid_fk foreign key(gid) references groups(id) 
); 
insert into emps(name,gid) values('哈哈',1); 
insert into emps(name,gid) values('呵呵',1); 
insert into emps(name,gid) values('嘻嘻',2); 
insert into emps(name,gid) values('笨笨',2);
Copy after login

Query which employees are in the "Development Department"

select g.name "部门",e.name "员工" 
from groups g inner join emps e 
on g.id = e.gid 
where g.name = '开发部'; 
-- 
select g.name "部门",e.name "员工" 
from groups g inner join emps e 
on g.id = e.gid 
where g.name = '开发部';
Copy after login

---------------------------- --------------------------

Many-to-many: Query which students "Zhao" has taught

Create students table

drop table if exists students; 
create table if not exists students( 
  id int(5) primary key auto_increment, 
  name varchar(10) not null 
); 
insert into students(name) values('哈哈'); 
insert into students(name) values('嘻嘻');
Copy after login

Create teachers table

drop table if exists teachers; 
create table if not exists teachers( 
  id int(5) primary key auto_increment, 
  name varchar(10) not null 
); 
insert into teachers(name) values('赵'); 
insert into teachers(name) values('刘');
Copy after login

Create middles table primary key(sid,tid) represents the joint primary key, The whole of these two fields must be unique

drop table if exists middles; 
create table if not exists middles( 
  sid int(5), 
  constraint sid_fk foreign key(sid) references students(id), 
  tid int(5), 
  constraint tid_fk foreign key(tid) references teachers(id), 
  primary key(sid,tid)  
); 
insert into middles(sid,tid) values(1,1); 
insert into middles(sid,tid) values(1,2); 
insert into middles(sid,tid) values(2,1); 
insert into middles(sid,tid) values(2,2);
Copy after login

Query which students "Zhao" has taught

select t.name "老师",s.name "学生" 
from students s inner join middles m inner join teachers t 
on (s.id=m.sid) and (m.tid=t.id) 
where t.name = '赵'; 
-- 
select t.name "老师",s.name "学生" 
from students s inner join middles m inner join teachers t  
on (s.id=m.sid) and (t.id=m.tid) 
where t.name = "赵";
Copy after login

-------------------- -------------------------------------------------- ----------------------------------

Identify employees who earn more than 5,000 yuan (inclusive) It is "high salary", otherwise it is marked as "starting salary"

Mark employees whose salary is NULL as "no salary"

Mark employees whose salary is more than 5,000 yuan (inclusive) as "high salary" , otherwise marked as "starting salary"

Mark employees with 7,000 yuan as "high salary", employees with 6,000 yuan as "medium salary", 5,000 yuan as "starting salary", otherwise mark as " Probationary salary"

----------------------------------------- -------------------------------------------------- --------------

Inner join (equivalent join): Query customer name, order number, order price

[Note: customers c inner join orders o uses an alias, and o will represent orders in the future]

select c.name "客户姓名",o.isbn "订单编号",o.price "订单价格" 
from customers c inner join orders o 
on c.id = o.customers_id; 
-- 
select c.name "客户姓名",o.isbn "订单编号",o.price "订单价格" 
from customers c inner join orsers o 
on c.id = o.customers_id;
Copy after login

on+Conditions for connecting two tables. Primary key of one table, foreign key of another table

Inner join: Only records that exist in two tables according to the connection conditions can be queried, which is somewhat similar to the intersection in mathematics

------------------- ----------------------------------

Outer connection: Group by customer, Query the name and order number of each customer

Outer join: You can query the records that exist in both tables according to the connection conditions, or you can also force the records of the other party based on one party even if they are not satisfied with the conditions. Can be queried

Outer join can be subdivided into:

<左外连接 : 以左侧为参照,left outer join表示 
select c.name,count(o.isbn) 
from customers c left outer join orders o 
on c.id = o.customers_id 
group by c.name; 
-- 
>右外连接 : 以右侧为参照,right outer join表示 
select c.name,count(o.isbn) 
from orders o right outer join customers c 
on c.id = o.customers_id 
group by c.name;
Copy after login

left outer join means that the content on the left will be displayed, for example, customers c left out join means that all the contents of a certain column in customers will be displayed Find them all

----------------------------------------- -------------
Self-connection: Find out whether AA’s boss is EE. Think of yourself as two tables. One on each side

select users.ename,bosss.ename 
from emps users inner join emps bosss 
on users.mgr = bosss.empno; 
select users.ename,bosss.ename 
from emps users left outer join emps bosss 
on users.mgr = bosss.empno;
Copy after login

------------------------------------------ -------------------------------------------------- ------
Demonstrate the function in MySQL (query manual)

Date and time function:

select addtime('2016-8-7 23:23:23','1:1:1');  时间相加 
select current_date(); 
select current_time(); 
select now(); 
select year( now() ); 
select month( now() ); 
select day( now() ); 
select datediff('2016-12-31',now());
Copy after login

String function :

select charset('哈哈'); 
select concat('你好','哈哈','吗'); 
select instr('www.baidu.com','baidu'); 
select substring('www.baidu.com',5,3);
Copy after login

Mathematical function:

select bin(10); 
select floor(3.14);//比3.14小的最大整数---正3 
select floor(-3.14);//比-3.14小的最大整数---负4 
select ceiling(3.14);//比3.14大的最小整数---正4 
select ceiling(-3.14);//比-3.14大的最小整数---负3,一定是整数值 
select format(3.1415926,3);保留小数点后3位,四舍五入 
select mod(10,3);//取余数 
select rand();//
Copy after login

Encryption function:

select md5('123456');

返回32位16进制数 e10adc3949ba59abbe56e057f20f883e  

演示MySQL中流程控制语句 

use json; 
drop table if exists users; 
create table if not exists users( 
  id int(5) primary key auto_increment, 
  name varchar(10) not null unique, 
  sal int(5) 
); 
insert into users(name,sal) values('哈哈',3000); 
insert into users(name,sal) values('呵呵',4000); 
insert into users(name,sal) values('嘻嘻',5000); 
insert into users(name,sal) values('笨笨',6000); 
insert into users(name,sal) values('明明',7000); 
insert into users(name,sal) values('丝丝',8000); 
insert into users(name,sal) values('君君',9000); 
insert into users(name,sal) values('赵赵',10000); 
insert into users(name,sal) values('无名',NULL);
Copy after login

将5000元(含)以上的员工标识为"高薪",否则标识为"起薪"

select name "姓名",sal "薪水", 
    if(sal>=5000,"高薪","起薪") "描述" 
from users;
Copy after login

将薪水为NULL的员工标识为"无薪"

select name "姓名",ifnull(sal,"无薪") "薪水" 
from users;
Copy after login

将5000元(含)以上的员工标识为"高薪",否则标识为"起薪"

select name "姓名",sal "薪水", 
    case when sal>=5000 then "高薪" 
    else "起薪" end "描述" 
from users;
Copy after login

将7000元的员工标识为"高薪",6000元的员工标识为"中薪",5000元则标识为"起薪",否则标识为"试用薪"

select name "姓名",sal "薪水", 
    case sal 
      when 3000 then "低薪" 
      when 4000 then "起薪" 
      when 5000 then "试用薪" 
      when 6000 then "中薪" 
      when 7000 then "较好薪" 
      when 8000 then "不错薪" 
      when 9000 then "高薪" 
      else "重薪" 
    end "描述" 
from users;
Copy after login


The above is the detailed content of Enhanced version of sql statements that you must know about MySQl database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to create oracle dynamic sql How to create oracle dynamic sql Apr 12, 2025 am 06:06 AM

SQL statements can be created and executed based on runtime input by using Oracle's dynamic SQL. The steps include: preparing an empty string variable to store dynamically generated SQL statements. Use the EXECUTE IMMEDIATE or PREPARE statement to compile and execute dynamic SQL statements. Use bind variable to pass user input or other dynamic values ​​to dynamic SQL. Use EXECUTE IMMEDIATE or EXECUTE to execute dynamic SQL statements.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

PostgreSQL performance optimization under Debian PostgreSQL performance optimization under Debian Apr 12, 2025 pm 08:18 PM

To improve the performance of PostgreSQL database in Debian systems, it is necessary to comprehensively consider hardware, configuration, indexing, query and other aspects. The following strategies can effectively optimize database performance: 1. Hardware resource optimization memory expansion: Adequate memory is crucial to cache data and indexes. High-speed storage: Using SSD SSD drives can significantly improve I/O performance. Multi-core processor: Make full use of multi-core processors to implement parallel query processing. 2. Database parameter tuning shared_buffers: According to the system memory size setting, it is recommended to set it to 25%-40% of system memory. work_mem: Controls the memory of sorting and hashing operations, usually set to 64MB to 256M

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles