SQL数据库的一些操作
//登陆
mysql -u root -h localhost -P 3306 -p
//创建一个名为test_lib的数据库
CREATE DATABASE test_lib
//查看有多少个database
show databases;
//查看某个database有多少个table
show tables;
//删除一个名为test_lib的数据库
DROP DATABASE test_lib
//选择test_lib数据库
USE test_lib
//添加一个包含3列的表(table)[参考](http://www.runoob.com/sql/sql-create-table.html)
CREATE TABLE table1
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size)
);
//创建带有主键的表
//主键必须包含唯一的值,主键列不能包含 NULL 值。
CREATE TABLE Persons (
Id_P INT NOT NULL,
LastName VARCHAR ( 255 ) NOT NULL,
FirstName VARCHAR ( 255 ),
Address VARCHAR ( 255 ),
City VARCHAR ( 255 ),
PRIMARY KEY ( Id_P )
)
//外键
//https://www.w3school.com.cn/sql/sql_foreignkey.asp
CREATE TABLE Orders (
Id_O INT NOT NULL,
OrderNo INT NOT NULL,
Id_P INT,
PRIMARY KEY ( Id_O ),
FOREIGN KEY ( Id_P ) REFERENCES Persons ( Id_P )
)
//删除一个表(table)
DROP TABLE table_name
//添加一个列(表头)
ALTER TABLE table_name ADD COLUMN column_name VARCHAR(45);
//删除一列
ALTER TABLE table1 DROP COLUMN column1;
//添加一行(两种方式,指定列,或者不指定列)
INSERT INTO table_name (column1,column2,column3,...) VALUES ('value1','value2','value3',...);
INSERT INTO table_name VALUES ('value1','value2','value3',...);
//删除一行
DELETE FROM table_name WHERE column5='CCC';
//显示test_lib的所有数据
SECLET * FROM test_lib
//查看当前使用的数据库
select database();
//查看数据库使用端口
show variables like 'port';
//查看数据库编码
show variables like 'character%';
//查看数据库的所有用户信息
select distinct concat('user: ''',user,'''@''',host,''';') as query from mysql.user;
//查看某个具体用户的权限
show grants for 'root'@'localhost';
//查看数据库当前连接数,并发数
show status like 'Threads%';
//查看数据文件存放路径
show variables like '%datadir%';
//where与and使用
SELECT * FROM `person` WHERE `Name` LIKE "%kun%" AND PersonType IS NOT NULL
//排序,默认asc(顺序)
SELECT * FROM `person` WHERE `Name` LIKE "%王%" ORDER BY `IdCardNumber`
//先按照PersonType排序(逆序),然后按照IdCardNumber排序(顺序)
SELECT * FROM `person` ORDER BY `PersonType` DESC,`IdCardNumber` ASC
//两表联查https://www.w3school.com.cn/sql/sql_join.asp
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons, Orders
WHERE Persons.Id_P = Orders.Id_P
//Left Join
SELECT
person.`Name`,
person.IdCardNumber,
customer_conference_person.SeatNumber
FROM
person
LEFT JOIN customer_conference_person ON person.IdCardNumber = customer_conference_person.IdNum
AND person.`Name` LIKE "%于%"
ORDER BY
person.`Name` DESC
多个表的join查询
//多表 https://www.cnblogs.com/xiaofeng028/p/4098965.html
SELECT
person.Age,
person.IdNum,
person.`Name`,
gun.GunNum,
gun.`Status`
FROM
person_gun
JOIN person ON person_gun.IdNum = person.IdNum
JOIN gun ON person_gun.GunNum = gun.GunNum