總結MySQL常用語句(持續更新)

2021-09-17 08:33:48 字數 2363 閱讀 8556

一、基礎記錄資料

常數列的最大值

select max

(article)

as article from shop;

獲取某列最大值的行

select * from shop where price =

(select max

(article) from shop)

;

按組排列的最大值

select article,

max(price)

as price from shop group

by article;

提取某列在組間的最大值

select article,dealer,price from shop s1 where price=

(select max

(s2.price) from shop s2 where s1.article =s2.article)

;

使用使用者變數

select @min_price:

=min

(price)

,@max_price:

=max

(price) from shop;

mysql5.7以上可以直接儲存json欄位,但是在查詢json欄位的時候,返回的結果總會帶雙引號「 " 」,下面是去掉雙引號的方法

//方法一

select json-

>

>

'$.attr' from table;

//方法二

select json_unquote

(json_extract

(json,

'$.attr'

)) from table;

刪除重覆記錄

思路:使用子查詢和諸如min這樣的聚合函式,任意選擇並保留乙個id(次例會保留重覆記錄的最小的id值的記錄)

delete from dupes

where id not in (select min

(id) from dupes

group by name)

二、實踐寫過的語句,當時可憋了好久~~!

時間戳以int值儲存,需要按著時間範圍統計資料

select

count(*

)from vote_votedata where from_unixtime

( create_time) between '2019-04-03 00:00:00'

and'2019-04-04 00:00:00'

;

微擎投票資料篩選(每個人每小時獲取票數)

select

title,

count

(distinct from_user )

,count

(distinct clientip )

, group_hour

from

(select

title,

from_user ,

clientip,

date_format

(from_unixtime

( create_time )

,'%y%m%d%h'

)as group_hour

from

ims_huiyi_weivote_log)

as r1

group

by title,group_hour

資料**兩個表,登入日誌表log_login和班級成員表class_user,兩個表以user_id關聯,日誌表中存在重複登入寫日誌的情況,編寫語句如下

select

count

(distinct user_id)

as login_count

from log_login

where user_id in

(select user_id as id

from class_user

where class_id =1)

;

參考:

[1] 吳津津. php與mysql權威指南[m]. 機械工業出版社, 2011.

[2]

[3] 劉春輝譯.sql經典例項[m].人民有點出版社,2018

[4]

Oracle常用語句 持續更新

select from v version select lengthb length from dualto date 2019 12 17 00 00 00 yyyy mm dd hh24 mm ss to date to char sysdate,yyyymm 01 yyyymmdd mont...

mysql常用語句 MySQL常用語句

create table student id int primary key auto increment comment 學號 name varchar 200 comment 姓名 age int comment 年齡 comment 學生資訊 修改表注釋 alter table studen...

MySQL建立表常用語句(持續更新中)

最近因工作需要,開始學習mysql,此文作為學習記錄,以備自己查閱。1.建立表 create table userinfo id int 4 primary key not null auto increment,自增列,如果只此一列,需定為主鍵,否則建立不成功 username varchar 5...