MySQL 是最流行的关系型数据库管理系统,在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System:关系数据库管理系统)应用软件之一。
在命令行中启动mysql:
mysql -u root -p
显示所有数据库:
SHOW DATABASES;
选择某个数据库:
USE app_yo;
显示当前数据库下所有的表:
SHOW TABLES;
查看表的列信息:
DESC table_name || SHOW INDEX FROM 数据表:
使用php连接数据库:
<?php $dbhost = 'localhost:3306'; // mysql服务器主机地址 $dbuser = 'root'; // mysql用户名 $dbpass = '123456'; // mysql用户名密码 $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo '数据库连接成功!'; mysqli_close($conn); ?>
使用nodejs连接数据库:
暂时空着,待会加
创建数据库:
CREATE DATABASE 数据库名;
创建数据库:
CREATE TABLE IF NOT EXISTS `runoob_tbl`(
`runoob_id` INT UNSIGNED AUTO_INCREMENT,
`runoob_title` VARCHAR(100) NOT NULL,
`runoob_author` VARCHAR(40) NOT NULL,
`submission_date` DATE,
PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
删除数据表
DROP TABLE table_name ;
插入数据
INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN );
查询数据
SELECT column_name,column_name
FROM table_name
[WHERE Clause]
[LIMIT N][ OFFSET M]
更新数据
UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]
删除数据
DELETE FROM table_name [WHERE Clause]
like语句
SELECT * from runoob_tbl WHERE runoob_author LIKE '%COM';
UNION 语句:用于将不同表中相同列中查询的数据展示出来;(不包括重复数据)
SELECT country FROM Websites
UNION
SELECT country FROM apps
ORDER BY country;
UNION ALL 语句:用于将不同表中相同列中查询的数据展示出来;(包括重复数据)
SELECT country FROM Websites
UNION ALL
SELECT country FROM apps
ORDER BY country;
GROUP BY 语句:
SELECT name, COUNT(*) FROM employee_tbl GROUP BY name;
JOIN语句,很重要,用来查询多张表的数据:
- INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
-
SELECT a.id,a.name AS '班级名称',b.name AS '年纪名称' FROM `sch_classes` a INNER JOIN `sch_grades` b ON a.`gradeid` = b.`id` WHERE a.`schoolid` =407; 等价于 SELECT a.id,a.name AS '班级名称',b.name AS '年纪名称' FROM `sch_classes` a, `sch_grades` b WHERE a.`gradeid` = b.`id` AND a.`schoolid` = 407;
-
- LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
-
SELECT a.id,a.name AS '班级名称',b.name AS '年纪名称' FROM `sch_classes` a LEFT JOIN `sch_grades` b ON a.`gradeid` = b.`id` WHERE a.`schoolid`;
-
- RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
NULL的使用
SELECT * FROM runoob_test_tbl WHERE runoob_count IS NULL;
SELECT * from runoob_test_tbl WHERE runoob_count IS NOT NULL;
事务
mysql> begin; # 开始事务 Query OK, 0 rows affected (0.00 sec) mysql> insert into runoob_transaction_test value(5); Query OK, 1 rows affected (0.01 sec) mysql> insert into runoob_transaction_test value(6); Query OK, 1 rows affected (0.00 sec) mysql> commit; # 提交事务 Query OK, 0 rows affected (0.01 sec)
ALTER 命令
插入列: alter table TABLE_NAME add column NEW_COLUMN_NAME varchar(20) not null;
删除,添加或修改表字段
删除:ALTER TABLE testalter_tbl DROP i;
增加:ALTER TABLE testalter_tbl ADD i INT FIRST;
修改:ALTER TABLE `classlist` CHANGE grade age INT;
修改表名
mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;
创建索引
CREATE INDEX suoyinName ON mytable(username(length));
