常用sql語句

創建數據庫:create database menagerie

建表:create table pet (name varchar(20), owner varchar(20), species varchar(20), sex char(1), birth date, death date)

employee表
在這裏插入圖片描述
pet表
在這裏插入圖片描述
shop表
在這裏插入圖片描述

更新表中名字爲Browser生日: update pet set birth = '1989-08-31' where name = 'Browser'

根據某字段排序:select name, species from pet order by birth desc

查詢日期年、月、日:select Year('2018-02-05') as years from pet
Month()、Day()

過濾某個字段值最大的整條記錄數據:select article, declear, price from pet where price = (select max(price) from shop)

每列最大值,根據某字段分組:select article, max(price) as price from shop group by article

聚合函數

count、sum、avg、max、min

count(1)、count()、count(列名)區別:
count(1)和count(
)執行結果同,查詢包括null列數據
count(列名)查詢不包括null列數據

執行效率上:
查詢字段不爲主鍵,count(1)>count(列名)>count(*)
查詢字段爲主鍵,count(列名)最優

內、左、右連接
select * from a inner(left|right) join b on a.A_ID=b.A_ID
in 和 exists
子查詢記錄少,主表較大,有索引:用in優
子查詢表大,有索引,用exists優

select * from a where A_ID in(1,2,3)
select * from a where exists (select A_ID from b)
case sex
when '1' then '男'
when '2' then '女'
else '其他' end

select *, case when salary < 5000 then "低等收入"
when salary >= 5000 and salary < 10000 then "中等收入"
when salary > 10000 then "高等收入" end as level from employee
where 、group by、 having、 order by排序
select name, sum(*) from employee_tb1 where id <> 1 group by name having sum(*) > 5 order by sum(*) desc

刪除、添加、修改表字段、字段類型、表名

alter table a drop
alter table a add i int
alter table a modify c char(10)
alter table a rename to b

常用函數

返回字符串s字符數:select char_length(s)
字符串s1、s2等多個字符串合併一個字符串:select concat(s1,s2) as s
返回第一個字符串s在字符串s1、s2中位置:select field(s1,s2)
返回字符串s的前n個字符:select left(s,n)
首尾去空格:trim(s)
從字符串s截取start位置處長度爲length的字符串:select substring(s, start, length)

索引

創建索引:create index id on b(B_ID)
修改表添加索引:alter table b add index price(B_price)
刪除索引:drop index price on b
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章