代码改变世界

sql的基本语法

2019-04-29 18:10  石吴玉  阅读(222)  评论(0编辑  收藏  举报

一. 数据库

1.查询服务器上有哪些数据库

show databases;

2.新建数据库

create database TestSqlSugar;

3.进入数据库

use TestSqlSugar;

4.删除数据库

drop database test;

二. 数据表

1.新建表 

(1) user

create table if not exists user(
    id int auto_increment,
    userName varchar(100) not null,
    userPassword varchar(500) not null,
    age int not null,
    regTime datetime default current_timestamp,
    departmentId int,
    primary key(id)
);

(2) department

create table if not exists department
(
    id int auto_increment,
    name varchar(100) not null,
    admin varchar(100) not null,
    phone varchar(15) not null,
    primary key(id)
);

2.表查询

select * from user
select * from department
### 包含条件查询
select * from user where id in (1);
### 分页limit temp1,temp2  调过temp1条temp2条数据
select * from user limit 1,2
### 双表左关联查询,表的重命名
select user.id as 'Id', user.departmentId as 'depId', user.userName as 'name' from user user left join department dep on(user.departmentId = dep.id)
### 两个Queryable的join
select
j1.* from (select user.id,user.userName,user.regTime,dep.name from user user inner join department dep on(user.departmentId=dep.id)) j1 inner join(select id,userName,userPassword,age,regTime,departmentId from user) j2 on(j1.id = j2.id)
### 三表关联查询,排序
select user.id,user.userName,user.userPassword,user.age,user.regTime,
user.departmentId,dep.id,dep.name,dep.admin,dep.phone,
userInfo.Id,userInfo.UserId,userInfo.Sex from user user Left JOIN department dep on(user.departmentId = dep.id)
Left JOIN userInfo userinfo ON(user.id = userinfo.userid) where(user.age=18 or dep.id=1 or userinfo.Sex='') order by user.regTime asc,dep.id desc;
###简化查询,两表关联(默认inner joinselect user.id,user.userName,dep.name from user user,department dep where (user.departmentId =dep.id)