天天看點

MySql基礎指令與查詢方法

這是我參與11月更文挑戰的第1天,活動詳情檢視: 2021最後一次更文挑戰

一、連接配接MySQL

  1. 首先安裝MySQL,然後開啟相關服務。
MySql基礎指令與查詢方法

、運作Navicat可視化工具

  1. 在Navicat中連接配接MySQL資料庫
MySql基礎指令與查詢方法
MySql基礎指令與查詢方法

三、MySQL的基礎指令

  • 首先啟動MySQL服務,然後通過下面的指令連接配接資料庫
mysql -u root -p
複制代碼      
  • 顯示目前存在的資料庫
show databases;
複制代碼      
  • 選擇想要操作的資料庫
use xxx;
複制代碼      
當出現Database changed表示切換成功!
  • 檢視目前資料庫都有哪些資料表
show tables;
複制代碼      
  • 檢視指定表中都有哪些資料
select * from xxx
複制代碼      
  • 指定查詢表中的哪些字段
select xxx from xxx;
複制代碼      
  • 指定查詢條件
select * from user where id=1;
select * from user where id>1;
複制代碼      
  • 建立一個資料庫
create database xxx;
複制代碼      
  • 添加資料表
create table users(
id int(11),
username varchar(255),
age int(3)
);
複制代碼      
  • 顯示表的結構
describe users;
複制代碼      
  • 向表中添加資料
insert into users(id,username,age) values (1,'王五',18);
複制代碼      
  • 修改指定的資料(将user表中id為1的字段的username修改為:王五)
update user set username="王五" where id=1;
複制代碼      
  • 修改多個字段的情況
update user set username="王五",id=666 where id=1;
複制代碼      
  • 删除指定的資料
delete from user where id=666;
複制代碼      
  • 對資料進行升序排列
select * from user order by id asc;
複制代碼      
  • 對資料進行降序排列
select * from user order by id desc;
複制代碼      
  • 對某個表統計數量
select count(1) from user;
複制代碼      
  • 隻查詢指定數量的資料
下面的方法隻會查詢前兩條資料。
select * from user limit 1;
複制代碼      
  • 跳過兩條,查詢1條
select * from user limit 2,1;
複制代碼      
  • 删除指定的表
drop table test;
複制代碼      
  • 删除指定的資料庫
drop database test;
複制代碼      

四、MySQL中的模糊查詢

  • 将郵件資訊中包含qq.com的都選出來
select * from class where email like "%qq.com%";
複制代碼      
  • 查詢email中以node開頭的
select * from class where email like "node%";
複制代碼      
  • 查詢email中以163.com結尾的元素
select * from class where email like "%163.com";
複制代碼      

五、MySQL中的分組函數

select avg(score) from class;
select count(score) from class;
select max(score) from class;
select min(score) from class;
select sum(score) from class;
複制代碼      
複合條件查詢
select * from class where score in (select max(score) from class);
複制代碼      

六、MySQL别名

select id,name as n,email as e,score as s from class;
複制代碼      

七、MySQL表與表之間的關系

表與表之間一般存在三種關系,即一對一,一對多和多對多關系。