search
HomeDatabaseMysql TutorialEnhanced version of sql statements that you must know about MySQl database

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);

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

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);

[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';

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

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('销售部');

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);

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 = '开发部';

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

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('嘻嘻');

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('刘');

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);

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 = "赵";

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

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;

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:

右外连接 : 以右侧为参照,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;

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;

------------------------------------------ -------------------------------------------------- ------
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());

String function :

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

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();//

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);

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

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

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

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

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

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

将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;


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
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.