**查詢 select
? 1.查詢所有欄位
? select * from 表名
? 2.查詢某一個欄位
? 1.基于表
? select 欄位名,欄位名 from 表名
? 2.基于運算式
? select 運算式,運算式;
? select 3+5,3*5;
? 3.基于函式
? --查看當前的資料庫
? select database();
? --查看當前時間
? select now();
? --查看當前的用戶名
? select user();
? --查看當前資料庫的版本
? select version();
? **3.**給欄位起別名
? select 欄位名 [as]別名 from 表名;
? **4.**給表起別名
? select 別名.欄位名 from 表名 as 別名;
? select a.username from admin as a;
? 5.資料庫.表名:
? select username from news.admin;
? **6.**完整格式
?
select 欄位名 from 表名
? [join條件]
? [where條件]
? [group by分組]
? [having欄位(二次篩選)]
? [order by欄位升序降序]
? [limit限制]
? 7.where****條件
? 1.比較:> < = != <> <= >=
? select * from admin where id>=2;
? 2.is[not] null
? select * from admin where username is not null;
? 3.[not]between …and
? 4.[not]in(值1,值2,值3);
? select * from admin where id in(1,2,3);
? 5.like ‘字串’ 模糊查詢
? –查詢admin表用戶名是 姓張 開頭
? 1._:匹配一個字符
? 2.%:匹配0個1個或者多個字符
select * from admin where username like '張_';
? select * from admin where username like '張%';
? --查詢用戶名中第二個字是張的用戶
select * from admin where username like '_張%';
? 8.[group by分組]
? 原理:對欄位相同的值進行分組,顯示分組相同的值得一個結果 一般欄位分組的那個欄位結合聚合函式使用聚合函式
? 1.count(欄位名):獲得每組的個數(count(*))包含null的值
? 2.avg(欄位):獲得每組的平均數
? 3.max(欄位):最大值
? 4.min(欄位):最小值
? 5.sum(欄位):求每組的和
? 9.having 欄位:二次過濾
? 說明:
? 1.where條件對欄位過濾
? 2.having條件是對一個結果的過濾,一般結合group by使用
1.order by 欄位名
? 升序:asc【默認】
? 降序:desc
select * from admin order by id desc;
2.limit [偏移量][長度]:獲取前多少條的記錄(新聞數量)
? 說明:
? 1.偏移量 offset 起始編號從0開始
? 2.長度:獲取的記錄數
? 3.計算偏移量
? 第一頁: 偏移量0 limit 0,5;
? 第二頁: 偏移量5 limit 5,5;
? 第三頁: 偏移量10 limit10,5;
? 偏移量=(當前頁-1)*長度
**3.**多表聯合查詢
? 1.格式
? select 欄位名,欄位名
? from 表1
? 連接型別 表2
? on 兩個表的邏輯關系
? 連接型別 表2
? on 兩個表的邏輯關系
–管理員表
create table cms_admin(
? id int unsigned key auto_increment,
? username varchar(10) not null unique,
? password char(32) not null,
? sex tinyint not null default 0,
? age tinyint not null
);
–創建cms_type
create table cms_type(
? id int unsigned key auto_increment,
? tname varchar(10) not null unique
);
–創建cms_news
create table cms_news(
? id int unsigned key auto_increment,
? title varchar(30) not null,
? content text not null,
? aid int not null,
? tid int not null,
? addtime timestamp not null default current_timestamp
);
–1.查詢cms_admin,cms_type,cms_news
– 欄位:新聞id,發布人是誰,新聞的標題
select n.id,username,title
from cms_admin as a
join cms_news as n
on a.id = n.aid
join cms_type as t
on t.id=n.tid;
–2.查詢每個管理員發布的新聞數量
–欄位:管理員id,管理員名稱,發布新聞的數量
select a.id,username,count(*)
from cms_admin as a
join cms_news as n
on a.id = n.aid
group by n.aid;
–3.每個分類下發布的新聞個數
–欄位:分類的id 分類的名稱 新聞個數
select t.id,tname,count(*)
from cms_type as t
join cms_news as n
on t.id = n.tid
group by n.tid;
–4.查詢cms_news,分類編號是2
– 的 按照addtime降序排序 的前2條記錄
select * from cms_news
where tid=2
order by addtime desc
limit 0,2;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/134501.html
標籤:其他
上一篇:全國第一條5G步行街開街;羅永浩回應直播有多賺錢:沒那么夸張;Windows Terminal 1.4發布|極客頭條
下一篇:監控平臺_專案存活監控(二)
