Mac安装mysql数据库&MySQL基础和MySQL在开发中常用的技术

一.安装步骤

打开终端,输入:

sudo vi ~/.bash_profile

输入 i

然后粘贴以下内容

# mysql

alias mysql='/usr/local/mysql/bin/mysql'

alias mysqladmin='/usr/local/mysql/bin/mysqladmin'

# ls

alias ls='ls -G'

ESC

输入 :wq

重新启动终端程序


在命令行中输入下面命令修改密码

mysqladmin -u root password "123456"



Last login: Sun Nov 27 22:27:51 on ttys000

tinghoudeMacBook:~ tinghou$ ls

Desktop    Downloads Movies    Pictures  VM Library cd

Documents  Library   Music     Public    Workspaces

tinghoudeMacBook:~ tinghou$ cd /usr/local/mysql/bin/

tinghoudeMacBook:bin tinghou$ ls

innochecksum               mysqlaccess

msql2mysql                 mysqlaccess.conf

my_print_defaults          mysqladmin

myisam_ftdump              mysqlbinlog

myisamchk                  mysqlbug

myisamlog                  mysqlcheck

myisampack                 mysqld

mysql                      mysqld-debug

mysql_client_test          mysqld_multi

mysql_client_test_embedded mysqld_safe

mysql_config               mysqldump

mysql_config_editor        mysqldumpslow

mysql_convert_table_format mysqlhotcopy

mysql_embedded             mysqlimport

mysql_find_rows            mysqlshow

mysql_fix_extensions       mysqlslap

mysql_plugin               mysqltest

mysql_secure_installation  mysqltest_embedded

mysql_setpermission        perror

mysql_tzinfo_to_sql        replace

mysql_upgrade              resolve_stack_dump

mysql_waitpid              resolveip

mysql_zap

tinghoudeMacBook:bin tinghou$ cd 

tinghoudeMacBook:~ tinghou$ mysql -u root -p

Enter password: tinghoudeMacBook

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 171

Server version: 5.6.12 MySQL Community Server (GPL)


Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.


Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.


Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema |

| mysql              |

| performance_schema |

| test               |

+--------------------+

4 rows in set (0.01 sec)


mysql> use test;

Database changed

mysql> exit;

Bye

tinghoudeMacBook:~ tinghou$ 

bogon:~ tinghou$ mysqladmin -u root password "123456"

bogon:~ tinghou$ mysql -u root -p

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 61

Server version: 5.6.12 MySQL Community Server (GPL)


Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.


Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.


Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> 

mysql> create database textdb1;

Query OK, 1 row affected (0.00 sec)


mysql> show create database textdb1;

+----------+--------------------------------------------------------------------+

| Database | Create Database                                                    |

+----------+--------------------------------------------------------------------+

| textdb1  | CREATE DATABASE `textdb1` /*!40100 DEFAULT CHARACTER SET latin1 */ |

+----------+--------------------------------------------------------------------+

1 row in set (0.00 sec)


mysql> use textdb1;

Database changed

mysql> select database();

+------------+

| database() |

+------------+

| textdb1    |

+------------+

1 row in set (0.00 sec)



mysql> select database();

+------------+

| database() |

+------------+

| textdb1    |

+------------+

1 row in set (0.00 sec)



mysql> create table t_user(

    -> id int,

    -> name varchar(20),

    -> sal double(4,3),

    -> birthday datetime,

    -> hiredate timestamp

    -> );

Query OK, 0 rows affected (0.03 sec)


mysql> show tables;

+-------------------+

| Tables_in_textdb1 |

+-------------------+

| t_user            |

+-------------------+

1 row in set (0.00 sec)


mysql> desc t_user;

+----------+-------------+------+-----+-------------------+-----------------------------+

| Field    | Type        | Null | Key | Default           | Extra                       |

+----------+-------------+------+-----+-------------------+-----------------------------+

| id       | int(11)     | YES  |     | NULL              |                             |

| name     | varchar(20) | YES  |     | NULL              |                             |

| sal      | double(4,3) | YES  |     | NULL              |                             |

| birthday | datetime    | YES  |     | NULL              |                             |

| hiredate | timestamp   | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |

+----------+-------------+------+-----+-------------------+-----------------------------+

5 rows in set (0.01 sec)


mysql> 



2.测试:

首先创建一个测试用的数据库

mysql> create database day06;

Query OK, 1 row affected (0.00 sec)


mysql> use day06;

Database changed

mysql> create table users(

    -> id int primary key auto_increment,

    -> name varchar(40),

    -> password varchar(40),

    -> email varchar(60),

    -> birthday date,

    -> )character set utf8 collate utf8_general_ci;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')character set utf8 collate utf8_general_ci' at line 7

mysql> create table users(

    -> id int primary key auto_increment,

    -> name varchar(40),

    -> password varchar(40),

    -> email varchar(60),

    -> birthday date

    -> )character set utf8 collate utf8_general_ci;

Query OK, 0 rows affected (0.03 sec)


mysql> insert into users(name,password,email,birthday) values('zs','123456','zs@sina.com','1980-12-04');

Query OK, 1 row affected (0.00 sec)


mysql> insert into users(name,password,email,birthday) values('ls','123','ls@sina.com','1990-01-01');

Query OK, 1 row affected (0.01 sec)


mysql> 


接着编写Java代码:
package com.me.jdbcdemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//使用JDBC技术实现查询数据库数据,并显示在控制台中
public class Demo1 {

	public static void main(String[] args) throws Exception {
		
	
		
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			
			
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", "root", "123456");
			
			Statement stmt = conn.createStatement();
			
			ResultSet rs = stmt.executeQuery("select password,email,birthday,id,name from users");
			
			 
			while(rs.next()){ 
				System.out.println(rs.getObject("password"));
				System.out.println(rs.getObject("id"));
				System.out.println(rs.getObject("name"));
				System.out.println(rs.getObject("birthday"));
				System.out.println(rs.getObject("email"));
				System.out.println("-----------------");
			}
		
			
			rs.close();
			stmt.close();
			conn.close();
			
		
	}

}

运行:enjoy it!



二.常见的SQL语句



bogon:~ tinghou$ mysql -u root -p

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 98

Server version: 5.6.12 MySQL Community Server (GPL)


Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.


Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.


Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema |

| day06              |

| mysql              |

| performance_schema |

| test               |

| testdb             |

| textdb1            |

+--------------------+

7 rows in set (0.01 sec)


mysql> use day06;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A


Database changed

mysql> net stop mysql;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'net stop mysql' at line 1

mysql> show tables;

+-----------------+

| Tables_in_day06 |

+-----------------+

| users           |

+-----------------+

1 row in set (0.00 sec)


mysql> desc users;

+----------+-------------+------+-----+---------+----------------+

| Field    | Type        | Null | Key | Default | Extra          |

+----------+-------------+------+-----+---------+----------------+

| id       | int(11)     | NO   | PRI | NULL    | auto_increment |

| name     | varchar(40) | YES  |     | NULL    |                |

| password | varchar(40) | YES  |     | NULL    |                |

| email    | varchar(60) | YES  |     | NULL    |                |

| birthday | date        | YES  |     | NULL    |                |

+----------+-------------+------+-----+---------+----------------+

5 rows in set (0.02 sec)


mysql> select *from users;

+----+------+----------+-------------+------------+

| id | name | password | email       | birthday   |

+----+------+----------+-------------+------------+

|  1 | zs   | 123456   | zs@sina.com | 1980-12-04 |

|  2 | ls   | 123      | ls@sina.com | 1990-01-01 |

+----+------+----------+-------------+------------+

2 rows in set (0.00 sec)


mysql> select name from users;

+------+

| name |

+------+

| zs   |

| ls   |

+------+

2 rows in set (0.00 sec)


mysql> /*从新创建一个数据库*/

mysql> /*创建一个雇员表 体验常见的数据库操作*/

mysql> create table emp(

    -> empno int,

    -> ename varchar(50),

    -> job varchar(50),

    -> mgr int,

    -> hiredate date,

    -> sal decimal(7,2),

    -> comm decimal(7,2),

    -> deptno int

    -> );

Query OK, 0 rows affected (0.05 sec)


mysql> show emp;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'emp' at line 1

mysql> desc emp;

+----------+--------------+------+-----+---------+-------+

| Field    | Type         | Null | Key | Default | Extra |

+----------+--------------+------+-----+---------+-------+

| empno    | int(11)      | YES  |     | NULL    |       |

| ename    | varchar(50)  | YES  |     | NULL    |       |

| job      | varchar(50)  | YES  |     | NULL    |       |

| mgr      | int(11)      | YES  |     | NULL    |       |

| hiredate | date         | YES  |     | NULL    |       |

| sal      | decimal(7,2) | YES  |     | NULL    |       |

| comm     | decimal(7,2) | YES  |     | NULL    |       |

| deptno   | int(11)      | YES  |     | NULL    |       |

+----------+--------------+------+-----+---------+-------+

8 rows in set (0.01 sec)


mysql> /*查询所有列*/

mysql> select * from emp;

Empty set (0.00 sec)


mysql> INSERT INTO emp values(7369,'SMITH','CLERK',7902,'1980-12-17',800,NULL,20);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600,300,30);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7521,'WARD','SALESMAN',7698,'1981-02-22',1250,500,30);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7566,'JONES','MANAGER',7839,'1981-04-02',2975,NULL,20);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250,1400,30);

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO emp values(7698,'BLAKE','MANAGER',7839,'1981-05-01',2850,NULL,30);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7782,'CLARK','MANAGER',7839,'1981-06-09',2450,NULL,10);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7788,'SCOTT','ANALYST',7566,'1987-04-19',3000,NULL,20);

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO emp values(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000,NULL,10);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500,0,30);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7876,'ADAMS','CLERK',7788,'1987-05-23',1100,NULL,20);

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO emp values(7900,'JAMES','CLERK',7698,'1981-12-03',950,NULL,30);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7902,'FORD','ANALYST',7566,'1981-12-03',3000,NULL,20);

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO emp values(7934,'MILLER','CLERK',7782,'1982-01-23',1300,NULL,10);

Query OK, 1 row affected (0.01 sec)


mysql> select * from emp;

+-------+--------+-----------+------+------------+---------+---------+--------+

| empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno |

+-------+--------+-----------+------+------------+---------+---------+--------+

|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |

|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |

|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |

|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |

|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |

|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |

|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |

|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |

|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |

|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 |

|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |

|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |

|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |

|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |

+-------+--------+-----------+------+------------+---------+---------+--------+

14 rows in set (0.00 sec)


mysql> /*查询指定列*/

mysql> select ename from emp;

+--------+

| ename  |

+--------+

| SMITH  |

| ALLEN  |

| WARD   |

| JONES  |

| MARTIN |

| BLAKE  |

| CLARK  |

| SCOTT  |

| KING   |

| TURNER |

| ADAMS  |

| JAMES  |

| FORD   |

| MILLER |

+--------+

14 rows in set (0.00 sec)


mysql> select ename,job from emp;

+--------+-----------+

| ename  | job       |

+--------+-----------+

| SMITH  | CLERK     |

| ALLEN  | SALESMAN  |

| WARD   | SALESMAN  |

| JONES  | MANAGER   |

| MARTIN | SALESMAN  |

| BLAKE  | MANAGER   |

| CLARK  | MANAGER   |

| SCOTT  | ANALYST   |

| KING   | PRESIDENT |

| TURNER | SALESMAN  |

| ADAMS  | CLERK     |

| JAMES  | CLERK     |

| FORD   | ANALYST   |

| MILLER | CLERK     |

+--------+-----------+

14 rows in set (0.00 sec)


mysql> /*创建一个学生表*/

mysql> create table stu(

    -> sid char(6),

    -> sname varchar(50),

    -> age int,

    -> gender varchar(50)

    -> );

Query OK, 0 rows affected (0.03 sec)


mysql> INSERT INTO stu VALUES('S_1001', 'liuYi', 35, 'male');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1002', 'chenEr', 15, 'female');

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO stu VALUES('S_1003', 'zhangSan', 95, 'male');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1004', 'liSi', 65, 'female');

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO stu VALUES('S_1005', 'wangWu', 55, 'male');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1006', 'zhaoLiu', 75, 'female');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1007', 'sunQi', 25, 'male');

Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO stu VALUES('S_1008', 'zhouBa', 45, 'female');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1009', 'wuJiu', 85, 'male');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1010', 'zhengShi', 5, 'female');

Query OK, 1 row affected (0.00 sec)


mysql> INSERT INTO stu VALUES('S_1011', 'xxx', NULL, NULL);

Query OK, 1 row affected (0.00 sec)


mysql> desc stu;

+--------+-------------+------+-----+---------+-------+

| Field  | Type        | Null | Key | Default | Extra |

+--------+-------------+------+-----+---------+-------+

| sid    | char(6)     | YES  |     | NULL    |       |

| sname  | varchar(50) | YES  |     | NULL    |       |

| age    | int(11)     | YES  |     | NULL    |       |

| gender | varchar(50) | YES  |     | NULL    |       |

+--------+-------------+------+-----+---------+-------+

4 rows in set (0.01 sec)


mysql> select *from stu;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1001 | liuYi    |   35 | male   |

| S_1002 | chenEr   |   15 | female |

| S_1003 | zhangSan |   95 | male   |

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1007 | sunQi    |   25 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1009 | wuJiu    |   85 | male   |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

11 rows in set (0.00 sec)


mysql> /*查询性别为女,并且年龄为50的记录*/

mysql> select * from stu where gender='female' and age<50;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1002 | chenEr   |   15 | female |

| S_1008 | zhouBa   |   45 | female |

| S_1010 | zhengShi |    5 | female |

+--------+----------+------+--------+

3 rows in set (0.00 sec)


mysql> /*查询学号为s_1001,s_1002)的记录*/

mysql> select * from stu where sid in('s_1001','s_1002');

+--------+--------+------+--------+

| sid    | sname  | age  | gender |

+--------+--------+------+--------+

| S_1001 | liuYi  |   35 | male   |

| S_1002 | chenEr |   15 | female |

+--------+--------+------+--------+

2 rows in set (0.00 sec)


mysql> /*查询学号为s_1001,或者姓名为liuYi的记录*/

mysql> select * from stu where sid ='s_1001' or sname = 'liuYi';

+--------+-------+------+--------+

| sid    | sname | age  | gender |

+--------+-------+------+--------+

| S_1001 | liuYi |   35 | male   |

+--------+-------+------+--------+

1 row in set (0.00 sec)


mysql> /*查询学号不是S_1001,S_1002,S_1003的记录*/

mysql> SELECT * FROM tab_student 

    -> WHERE s_number NOT IN ('S_1001','S_1002','S_1003');

ERROR 1146 (42S02): Table 'day06.tab_student' doesn't exist

mysql> SELECT * FROM tab_student  WHERE s_number NOT IN ('S_1001','S_1002','S_1003');

ERROR 1146 (42S02): Table 'day06.tab_student' doesn't exist

mysql> SELECT * FROM stu  WHERE s_number NOT IN ('S_1001','S_1002','S_1003');

ERROR 1054 (42S22): Unknown column 's_number' in 'where clause'

mysql> select * from stu where sid not in('S_1001','S_1002','S_1003');

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1007 | sunQi    |   25 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1009 | wuJiu    |   85 | male   |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

8 rows in set (0.00 sec)


mysql> /*查询年龄为Null的记录*/

mysql> select *from stu where age is null;

+--------+-------+------+--------+

| sid    | sname | age  | gender |

+--------+-------+------+--------+

| S_1011 | xxx   | NULL | NULL   |

+--------+-------+------+--------+

1 row in set (0.00 sec)


mysql> /*查询年龄在20岁到40岁之间的学生*/

mysql> select *from stu where age>=20 and age<=40;

+--------+-------+------+--------+

| sid    | sname | age  | gender |

+--------+-------+------+--------+

| S_1001 | liuYi |   35 | male   |

| S_1007 | sunQi |   25 | male   |

+--------+-------+------+--------+

2 rows in set (0.00 sec)


mysql> select *from stu where age between 20 and 40;

+--------+-------+------+--------+

| sid    | sname | age  | gender |

+--------+-------+------+--------+

| S_1001 | liuYi |   35 | male   |

| S_1007 | sunQi |   25 | male   |

+--------+-------+------+--------+

2 rows in set (0.01 sec)


mysql> /*查询性别非男生的学生记录*/

mysql> select *from stu where gender<>'male';

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1002 | chenEr   |   15 | female |

| S_1004 | liSi     |   65 | female |

| S_1006 | zhaoLiu  |   75 | female |

| S_1008 | zhouBa   |   45 | female |

| S_1010 | zhengShi |    5 | female |

+--------+----------+------+--------+

5 rows in set (0.00 sec)


mysql> select *from stu where not gender='male';

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1002 | chenEr   |   15 | female |

| S_1004 | liSi     |   65 | female |

| S_1006 | zhaoLiu  |   75 | female |

| S_1008 | zhouBa   |   45 | female |

| S_1010 | zhengShi |    5 | female |

+--------+----------+------+--------+

5 rows in set (0.01 sec)


mysql> /*查询姓名不为null的记录*/

mysql> select *from stu where sname is not null;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1001 | liuYi    |   35 | male   |

| S_1002 | chenEr   |   15 | female |

| S_1003 | zhangSan |   95 | male   |

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1007 | sunQi    |   25 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1009 | wuJiu    |   85 | male   |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

11 rows in set (0.00 sec)


mysql> select *from stu where not sname is null;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1001 | liuYi    |   35 | male   |

| S_1002 | chenEr   |   15 | female |

| S_1003 | zhangSan |   95 | male   |

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1007 | sunQi    |   25 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1009 | wuJiu    |   85 | male   |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

11 rows in set (0.00 sec)


mysql> /*模糊查询:当想查询mysql> 模糊查询:当想查询姓名当中包含了字母a的时候 询mysql> 模糊查询:当想查询姓名当中包含了字母a的时候就需要使用模糊查询了。模糊查询需要使用关键字 like 通配符: _ 任意一个字符 %:任意0~n个字符  '%张%' '张_'*/

    -> 

    ->  

    -> select *from stu;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '模糊查询:当想查询姓名当中包含了字母a的时候就需要使用' at line 1

mysql> /*查询由5个字母构成的学生记录*/

mysql> select * from stu where sname like '-----';

Empty set (0.00 sec)


mysql> select *from stu where sname like '---'

    -> ;

Empty set (0.00 sec)


mysql> select *from stu where sname like '--';

Empty set (0.00 sec)


mysql> select * from stu where sname LIKE '------';

Empty set (0.00 sec)


mysql> /*查询姓名由5个字母构成,并且第5个字母为“i”的学生记录*/

mysql> select * from stu where sname like '----i';

Empty set (0.00 sec)


mysql> select from stu;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from stu' at line 1

mysql> selcet *from stu;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'selcet *from stu' at line 1

mysql> select * from stu;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1001 | liuYi    |   35 | male   |

| S_1002 | chenEr   |   15 | female |

| S_1003 | zhangSan |   95 | male   |

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1007 | sunQi    |   25 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1009 | wuJiu    |   85 | male   |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

11 rows in set (0.00 sec)


mysql> /**去去除重复记录(两行或两行以上记录中系列的上的数据都相同),例如emp表 中sal字段就存在相同的记录。当只查询emp表的sal字段时,那么会出现重复记录,那么想 去除重复记录,需要使用DISTINCT:*/

mysql> select distinct sal from emp;

+---------+

| sal     |

+---------+

|  800.00 |

| 1600.00 |

| 1250.00 |

| 2975.00 |

| 2850.00 |

| 2450.00 |

| 3000.00 |

| 5000.00 |

| 1500.00 |

| 1100.00 |

|  950.00 |

| 1300.00 |

+---------+

12 rows in set (0.01 sec)


mysql> select sal from emp;

+---------+

| sal     |

+---------+

|  800.00 |

| 1600.00 |

| 1250.00 |

| 2975.00 |

| 1250.00 |

| 2850.00 |

| 2450.00 |

| 3000.00 |

| 5000.00 |

| 1500.00 |

| 1100.00 |

|  950.00 |

| 3000.00 |

| 1300.00 |

+---------+

14 rows in set (0.00 sec)


mysql> /*查看雇员的月薪与佣金之和*/

mysql> select *,sal+comm from emp;

+-------+--------+-----------+------+------------+---------+---------+--------+----------+

| empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno | sal+comm |

+-------+--------+-----------+------+------------+---------+---------+--------+----------+

|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |     NULL |

|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |  1900.00 |

|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |  1750.00 |

|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |     NULL |

|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |  2650.00 |

|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |     NULL |

|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |     NULL |

|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |     NULL |

|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |     NULL |

|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 |  1500.00 |

|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |     NULL |

|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |     NULL |

|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |     NULL |

|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |     NULL |

+-------+--------+-----------+------+------------+---------+---------+--------+----------+

14 rows in set (0.00 sec)


mysql> /** comm列有很多记录的值为NULL,因为任何东西与NULL相加结果还是NULL,所以 结算结果可能会出现NULL。下面使用了把NULL转换成数值0的函数IFNULL:*/

mysql> select *,sal+ifnull(comm,0) from emp;

+-------+--------+-----------+------+------------+---------+---------+--------+--------------------+

| empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno | sal+ifnull(comm,0) |

+-------+--------+-----------+------+------------+---------+---------+--------+--------------------+

|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |             800.00 |

|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |            1900.00 |

|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |            1750.00 |

|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |            2975.00 |

|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |            2650.00 |

|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |            2850.00 |

|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |            2450.00 |

|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |            3000.00 |

|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |            5000.00 |

|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 |            1500.00 |

|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |            1100.00 |

|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |             950.00 |

|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |            3000.00 |

|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |            1300.00 |

+-------+--------+-----------+------+------------+---------+---------+--------+--------------------+

14 rows in set (0.00 sec)


mysql> /**给列名添加别名:在上面查询中出现列名为sal+IFNULL(comm,0),这很不美观,现在我们给这一列给出一个别名,为total:*/

mysql> select *,sal+ifnull(comm,0) as total from emp;

+-------+--------+-----------+------+------------+---------+---------+--------+---------+

| empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno | total   |

+-------+--------+-----------+------+------------+---------+---------+--------+---------+

|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |  800.00 |

|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 | 1900.00 |

|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 | 1750.00 |

|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 | 2975.00 |

|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 | 2650.00 |

|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 | 2850.00 |

|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 | 2450.00 |

|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 | 3000.00 |

|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 | 5000.00 |

|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 | 1500.00 |

|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 | 1100.00 |

|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |  950.00 |

|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 | 3000.00 |

|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 | 1300.00 |

+-------+--------+-----------+------+------------+---------+---------+--------+---------+

14 rows in set (0.01 sec)


mysql> /**排序  order by 列名 asc(默认) desc*/

mysql> select * from stu order by age desc;

+--------+----------+------+--------+

| sid    | sname    | age  | gender |

+--------+----------+------+--------+

| S_1003 | zhangSan |   95 | male   |

| S_1009 | wuJiu    |   85 | male   |

| S_1006 | zhaoLiu  |   75 | female |

| S_1004 | liSi     |   65 | female |

| S_1005 | wangWu   |   55 | male   |

| S_1008 | zhouBa   |   45 | female |

| S_1001 | liuYi    |   35 | male   |

| S_1007 | sunQi    |   25 | male   |

| S_1002 | chenEr   |   15 | female |

| S_1010 | zhengShi |    5 | female |

| S_1011 | xxx      | NULL | NULL   |

+--------+----------+------+--------+

11 rows in set (0.01 sec)


mysql> /*查询所有雇员,按月薪降序排序,如果月薪相同时,按编号升序排序*/

mysql> select * from emp order by desc empno asc;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc empno asc' at line 1

mysql> select * from emp order by sal desc,empno asc;

+-------+--------+-----------+------+------------+---------+---------+--------+

| empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno |

+-------+--------+-----------+------+------------+---------+---------+--------+

|  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |

|  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |

|  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |

|  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |

|  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |

|  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |

|  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |

|  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    0.00 |     30 |

|  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |

|  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |

|  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |

|  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |

|  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |

|  7369 | SMITH  | CLERK     | 7902 | 1980-12-17 |  800.00 |    NULL |     20 |

+-------+--------+-----------+------+------------+---------+---------+--------+

14 rows in set (0.00 sec)


mysql> /** 聚合函数  sum avg max min count*/

mysql> 聚合函数是用来做纵向运算的函数:

    -> λCOUNT():统计指定列不为NULL的记录行数;

    -> λMAX():计算指定列的最大值,如果指定列是字符串类型,那么使用字符串排序运 算;

    -> λMIN():计算指定列的最小值,如果指定列是字符串类型,那么使用字符串排序运 算;

    -> λSUM():计算指定列的数值和,如果指定列类型不是数值类型,那么计算结果为0; 

    -> λAVG():计算指定列的平均值,如果指定列类型不是数值类型,那么计算结果为0; 

    -> */

    -> select count(*) as cnt from emp;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '聚合函数是用来做纵向运算的函数:


λCOUNT():统计指定列不' at line 1

mysql> select count(*) as cnt from emp;

+-----+

| cnt |

+-----+

|  14 |

+-----+

1 row in set (0.01 sec)


mysql> /*上面是查询emp表中记录数*/

mysql> /*查询emp表中有佣金的人数*/

mysql> select count(comm)cnt from emp;

+-----+

| cnt |

+-----+

|   4 |

+-----+

1 row in set (0.00 sec)


mysql> /*统计月薪与佣金纸盒大于2500元的人数*/

mysql> select count(*) as cnt from emp where sal+ifnull(comm,0)>2500;

+-----+

| cnt |

+-----+

|   6 |

+-----+

1 row in set (0.01 sec)


mysql> /*查询有佣金的人数,有领导的人数*/

mysql> select count(comm),count(mgr)from emp;

+-------------+------------+

| count(comm) | count(mgr) |

+-------------+------------+

|           4 |         13 |

+-------------+------------+

1 row in set (0.00 sec)


mysql> /*查询所有雇员月薪和,以及所有雇员佣金和*/

mysql> select sum(sal),sum(comm) from emp;

+----------+-----------+

| sum(sal) | sum(comm) |

+----------+-----------+

| 29025.00 |   2200.00 |

+----------+-----------+

1 row in set (0.00 sec)


mysql> /*查询所有雇员月薪+佣金和*/

mysql> SELECT SUM(sal+IFNULL(comm,0)) FROM emp;

+-------------------------+

| SUM(sal+IFNULL(comm,0)) |

+-------------------------+

|                31225.00 |

+-------------------------+

1 row in set (0.00 sec)


mysql> /*统计所有员工平均工资*/

mysql> SELECT AVG(sal) FROM emp;

+-------------+

| AVG(sal)    |

+-------------+

| 2073.214286 |

+-------------+

1 row in set (0.00 sec)


mysql> /*λ查询最高工资和最低工资:

   /*> select max(sal),min(sal)from emp;

   /*> */

mysql> select max(sal),min(sal)from emp;

+----------+----------+

| max(sal) | min(sal) |

+----------+----------+

|  5000.00 |   800.00 |

+----------+----------+

1 row in set (0.00 sec)


mysql> /*查询每个部门的部门编号和每个部门的工资和*/

mysql> select deptno,sum(sal) from emp group by deptno;

+--------+----------+

| deptno | sum(sal) |

+--------+----------+

|     10 |  8750.00 |

|     20 | 10875.00 |

|     30 |  9400.00 |

+--------+----------+

3 rows in set (0.00 sec)


mysql> /*查询每个部门的部门编号以及每个部门的人数*/

mysql> select deptno,count(*) from emp group by deptno;

+--------+----------+

| deptno | count(*) |

+--------+----------+

|     10 |        3 |

|     20 |        5 |

|     30 |        6 |

+--------+----------+

3 rows in set (0.00 sec)


mysql> /*查询每个部门的部门编号以及每个部门工资大于1500的人数*/

mysql> select depno,count(*) from emp where sal>1500 group by deptno;

ERROR 1054 (42S22): Unknown column 'depno' in 'field list'

mysql> select deptno,count(*) from emp where sal>1500 group by deptno;

+--------+----------+

| deptno | count(*) |

+--------+----------+

|     10 |        2 |

|     20 |        3 |

|     30 |        2 |

+--------+----------+

3 rows in set (0.00 sec)


mysql> 




一、SQL简介

Structured Query Language 结构化查询语言

作用:与数据库进行交互

知识扩展:

SQL标准,由ANSI(美国标准学会,属于ISO的核心成员)进行管理和维护的。

数据库厂商都支持该标准,并进行了扩展。扩展的部分,一般称之为方言。

 

SQL标准和方言:普通话和方言。

二、常用的数据库

1、Oracle

2、DB2

3、MySQL

4、SQL Server

三、安装MySQL

验证是否安装成功:

登录数据库:

shell>mysql -u root -p

四、数据库的基本概念:

知识点:使用关键字作为表名或数据库名或字段名,使用``(反引号)引起来

约定:shell>命令 windows命令

  mysql>命令 mysql命令或语句

 

User类对应User表结构

User对象对应User表中的一条记录

五、SQL语句的分类:

*DDL:Data Definition Language数据定义语言

*DML:Data Manipulation Language 数据操作语言

DCL:Data Control Language 数据控制语言

*DQL:Data Query Language 数据查询语言

*TPL:事务处理语言

 

六、DDL:数据定义语言

作用:定义数据库或表结构用的

关键字:CREATE ALTER DROP

6.1数据库结构操作:

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

 

创建一个名称为mydb1的数据库。

mysql>CREATE DATABASE mydb1;       (字符集采用数据库默认的--安装时的那个)

查看数据库的创建细节

mysql>SHOW CREATE DATABASE mydb1;

查看当前所有的数据库

mysql>SHOW DATABASES;

创建一个使用gbk字符集的mydb2数据库。

mysql>CREATE DATABASE mydb2 CHARACTERSET gbk;

创建一个使用utf8字符集,并带校对规则的mydb3数据库。

mysql>CREATE DATABASE mydb3 CHARACTERSET utf8 COLLATE utf8_general_ci;

查看当前数据库服务器中的所有数据库

mysql>SHOW DATABASES;

查看前面创建的mydb2数据库的定义信息

mysql>SHOW CREATE DATABASE mydb2;

删除前面创建的mydb1数据库

mysql>DROP DATABASE mydb1;

查看服务器中的数据库,并把mydb2的字符集修改为utf8;

mysql>ALTER DATABASE mydb2 CHARACTER SETutf8;

 

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

6.2表结构操作

创建表之前要先选择数据库。

选择数据库

mysql>USE mydb2;

创建一个员工表

mysql>CREATE TABLE employee(

           idint,

           namevarchar(100),

           gendervarchar(10),

           birthdaydate,

           entry_datedate,

           jobvarchar(100),

           salaryfloat(8,2),

           resumetext

);

查看当前数据库中的所有表

mysql>SHOW TABLES;

查看表的创建细节

mysql>SHOW CREATE TABLE employee;

在上面员工表的基本上增加一个image列。

mysql>ALTER TABLE employee ADD imageblob;

修改job列,使其长度为60。

mysql>ALTER TABLE employee MODIFYjob varchar(60);

删除image列。

mysql>ALTER TABLE employee DROP image;

表名改为user。

mysql>RENAME TABLE employee TO user;

修改表的字符集为utf8

mysql>ALTER TABLE user CHARACTER SETgbk;

列名name修改为username

mysql>ALTER TABLE user CHANGEname username varchar(100);

 

七、DML:数据操作语言

作用:操作的是表中的记录(数据)

关键字:INSERT UPDATE DELETE

 

MySQL:

字符串类型   使用单引号引起来   ‘abcdefg’

日期时间 使用单引号引起来   ‘2001-01-08’

特殊值   null

 

7.1插入数据

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

向user表中插入三条员工信息

mysql>INSERT INTOuser (id,username,gender,birthday,entry_date,job,salary,resume)VALUES(1,'zhw','male','1990-08-09','2014-03-29','CTO',10000,'description');

mysql>INSERT INTO userVALUES(2,'hch','female','1989-08-09','2014-03-29','CEO',10000,'aaaaaa');

mysql>INSERT INTO user (id,username,gender,birthday,entry_date,job,salary,resume)VALUES(3,'皇甫张军','male','1990-08-09','2014-03-29','UFO',10000,'帅锅一枚');

 

 

告知服务器客户端使用的编码为gbk

mysql>set character_set_client=gbk;

告知服务器客户端查看结果集用的编码为gbk;

mysql>set character_set_results=gbk;

 

 

7.2更新数据

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

 

将所有员工薪水修改为5000元。

mysql>UPDATE user SET salary=5000;

将姓名为’zhw’的员工薪水修改为3000元。

mysql>UPDATE user SET salary=3000 WHEREusername=’zhw’;

将姓名为’hch’的员工薪水修改为4000元,job改为ccc。

mysql>UPDATE user SET salary=4000,job=’ccc’WHERE username=’hch’;

将”皇甫张军”的薪水在原有基础上增加1000元。         

mysql>UPDATE user SET salary=salary+1000where username=’皇甫张军’;

 

7.3删除数据

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

删除表中名称为’zhw’的记录。

msyql>DELETE FROM user WHERE username=’zhw’;

删除表中所有记录。

方式一:

mysql>DELETE FROM user;

方式二:(属于DDL语句)

mysql>TRUNCATE TABLE user; 把整张表格摧毁,然后重建的表结构。这比一行一行的删除行要快很多

 

八、DQL:数据查询语言

作用:查询

关键字:SELECT

8.1简单查询

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

查询表中所有学生的信息。

mysql>SELECT * FROM student;

查询表中所有学生的姓名和对应的英语成绩。

mysql>SELECT name,english FROMstudent;   (投影查询)

过滤表中重复数据。

msyql>SELECT DISTINCT english FROMstudent;

在所有学生数学分数上加10分特长分。

mysql>SELECT name,math+10 FROM student;

统计每个学生的总分。

mysql>SELECT name,chinese+english+mathFROM student;

使用别名表示学生分数。

mysql>SELECT name AS 姓名,chinese+english+math 总分 FROM student;

 

查询姓名为王五的学生成绩

msyql>SELECT * FROM student WHERE name='王五';

查询英语成绩大于90分的同学

mysql>SELECT * FROM student WHEREenglish>90;

查询总分大于200分的所有同学

mysql>SELECT * FROM student WHERE(chinese+english+math)>200;

 

查询英语分数在 80-90之间的同学。

mysql>SELECT * FROM student WHERE englishBETWEEN 80 AND 90;

查询数学分数为89,90,91的同学。

mysql>SELECT * FROM student WHERE mathIN (89,90,91);

查询所有姓李的学生成绩。

mysql>SELECT * FROM student WHERE nameLIKE ‘李%’;

查询数学分>80,语文分>80的同学。

mysql>SELECT * FROM student WHEREmath>80 AND chinese>80;

 

 

对数学成绩排序后输出。

mysql>SELECT name,math FROM studentORDER BY math;

对总分排序后输出,然后再按从高到低的顺序输出

mysql>SELECT name,chinese+english+mathFROM student ORDER BY chinese+english+math DESC;

对姓李的学生语文成绩排序输出(由高到低)

msyql>SELECT name,chinese FROM studentWHERE name LIKE ‘李%’ ORDER BY chineseDESC;

 

九、数据完整性

1、数据完整性是为了保证插入到数据中的数据是正确的,它防止了用户可能的输入错误

2、分为三类

l  实体完整性

l  域完整性

l  参照完整性

9.1实体完整性

规定表的一行(即每一条记录)在表中是唯一的实体。实体完整性通过表的主键来实现

 

主键的特点:不能为null,必须有值,且不能重复。

主键分类:

逻辑主键:不代表实际意义,只是区分不同记录用的。比如id

业务主键:代表者具体的实际意义。比如身份证号  用户名

CREATE TABLE t2(

           idint PRIMARY KEY,#PRIMARY KEY 声明id是主键

           namevarchar(100)

);

 

CREATE TABLE t4(

           idint,

           namevarchar(100),

PRIMARY KEY(id)

);

 

 

CREATE TABLE t3(

           idint PRIMARY KEY auto_increment,#auto_increment 数据库自动增长

           namevarchar(100)

);

 

9.2域完整性

指数据库表的列(即字段)必须符合某种特定的数据类型或约束。

 

非空约束:not null

唯一约束:unique

 

CREATE TABLE t6(

           idint PRIMARY KEY auto_increment,

           usernamevarchar(100) not null unique, 非空和唯一约束

           gendervarchar(10) not null  非空约束

);

9.3参照完整性(多表)

表间的关系:

一对多(用的最多)

多对多(用的很多)

一对一(几乎不用)

 

9.3.1一对多:部门和员工的关系

CREATE TABLE department(

           idint primary key,

           namevarchar(100)

);

 

CREATE TABLE employee(

           idint primary key,

           namevarchar(100),

           salaryfloat(8,2),

           department_idint,

           CONSTRAINTdepartment_id_fk FOREIGN KEY(department_id) REFERENCES department(id)

);

 

9.3.2多对多:老师和学员

CREATE TABLE teacher(

           idint primary key,

           namevarchar(100),

           salaryfloat(8,2)

);

CREATE TABLE student(

           idint primary key,

           namevarchar(100),

           gradevarchar(10)

);

CREATE TABLE teacher_student(

           t_idint,

           s_idint,

           CONSTRAINTt_id_fk FOREIGN KEY(t_id) REFERENCES teacher(id),

           CONSTRAINTs_id_fk FOREIGN KEY(s_id) REFERENCES student(id),

           PRIMARYKEY(t_id,s_id)

);

 

9.3.3一对一(了解)

l  按照外键关联:

CREATE TABLE person(

           idint primary key,

           namevarchar(100)

);

CREATE TABLE idcard(

           idint primary key,

           numbervarchar(20),

           person_idint unique,

           CONSTRAINTperson_id_fk FOREIGN KEY(person_id) REFERENCES person(id)

);

 

l  按照主键关联:

CREATE TABLE person(

           idint primary key,

           namevarchar(100)

);

CREATE TABLE idcard(

           idint primary key,

           numbervarchar(20),

           CONSTRAINTperson_id_fk FOREIGN KEY(id) REFERENCES person(id)

);

 

十、DQL:数据查询复杂的(多表)

10.1连接查询(面试几率很大)

基本语法形式:FROM 1连接类型2 [on连接条件][where 筛选条件]

约定:表1在连接类型的左边,称之为左表

  2在连接类型的右边,称之为右表

 

l  交叉连接:cross join

返回左表和右表的笛卡尔积(左表5条记录 ,右表6条记录 5*6=30条)

select * from customer,orders;

select * from customer cross join orders;

l  内连接:inner join

返回满足连接条件的所有记录。

隐式内连接:(不使用inner join关键字)

select c.*,o.* from customer c,orders o where c.id=o.customer_id;

显式内连接:(使用inner join关键字)

select * from customer c inner join orders o on c.id=o.customer_id;

l  外连接:outer join

左外连接:left outer join=left join

返回满足连接条件的所有记录,同时返回左表中剩余的其他记录

查询所有客户,有订单的把订单也显示出来

select * from customer c left outer join orders o onc.id=o.customer_id;

右外连接:right outer join=right join

返回满足连接条件的所有记录,同时返回右表中剩余的其他记录

查询所有订单,同时打印订单所属的客户

select * from customer c right outer join orders o onc.id=o.customer_id;

10.2子查询

子查询也叫嵌套查询,是指在select子句或者where子句中又嵌入select查询语句

查询“陈冠希”的所有订单信息

 

select id fromcustomer where name=’陈冠希’;

select * fromorders where customer_id=1;

 

子查询:

select * fromorders where customer_id=(select id from customer where name=’陈冠希’);

10.3联合查询

union关键字。

联合查询能够合并两条查询语句的查询结果,去掉其中的重复数据行,然后返回没有重复数据行的查询结果

SELECT * FROM orders WHERE price>200UNION SELECT * FROM orders WHERE customer_id=1;

 

10.4报表查询(使用数据库提供的函数)

统计一个班级共有多少学生?

msyql>SELECT COUNT(*) FROM student;

统计数学成绩大于90的学生有多少个?

mysql>SELECT COUNT(*) FROM student WHEREmath>90;

统计总分大于250的人数有多少?

mysql>SELECT COUNT(*) FROM student WHERE(chinese+english+math)>250;

 

统计一个班级数学总成绩?

mysql>SELECT SUM(math) FROM student;

统计一个班级语文、英语、数学各科的总成绩

mysql>SELECTSUM(chinese),SUM(english),SUM(math) FROM student;

统计一个班级语文、英语、数学的成绩总和

mysql>SELECT SUM(chinese+english+math)FROM student;

统计一个班级语文成绩平均分

mysql>SELECT SUM(chinese)/COUNT(*) FROMstudent;

 

求一个班级数学平均分?

mysql>SELECT AVG(math) FROM student;

求一个班级总分平均分

mysql>SELECT AVG(chinese+english+math)FROM student;

 

求班级语文最高分和数学最低分

mysql>SELECT MAX(chinese) FROM student;

mysql>SELECT MIN(math) FROM student;

 

 

对订单表中商品归类后,显示每一类商品的总价

mysql>SELECT product,SUM(price) FROMorders GROUP BY product;

查询购买了几类商品,并且每类总价大于100的商品

mysql>SELECT product,SUM(price) FROMorders GROUP BY product HAVING SUM(price)>100;

 

十一、MySQL数据库的备份与恢复

1、备份

2、恢复
前提:必须先创建数据库的名称

方式一:进入MySQL

方式二:不用进入MySQL

 

 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值