1. 程式人生 > 實用技巧 >MySQL筆記---單表查詢1

MySQL筆記---單表查詢1

MySQL筆記---單表查詢1

/**
  單表查詢
 */
show databases;
use db_26;
show tables;

select *
from tab_3;
desc tab_3;
insert into tab_3 (tid, tname, tage, sex)
values (1001,
        concat('韓寒', 1),
        truncate((rand() * 8 + 18), 0),
        (if(rand() > 0.5, '男', '女')));


/**
  單表查詢
 */
select *
from tab_3;
# 查詢所有行的所有列, select * from 表名
select tid, tname
from tab_3;
# 查詢所有行的指定列 select 列名,列名 from 表名
select tage + 1, concat('我叫', tname, ' 今年', tage, ' 歲')
from tab_3;
# 列運算 + - * / %(mod)
# concat(str,str2,str3,.....) 字串拼接運算

select distinct tname
from tab_3;
select distinct tname, tage
from tab_3;
# 去重 distinct 重複的記錄顯示一次

# 聚合函式: sum max min avg count
select sum(tage), min(tage), max(tage), avg(tage), count(tage), count(*)
from tab_3;
# count 不為 null 的數量 ,count(*) 總記錄數
# avg ,計算非 null 的值

insert into tab_3 (tid, tname)
values (23, '張三');
# 不設定,預設為 null

# 求所有記錄的平均年齡
select sum(tage) / count(*), avg(tage)
from tab_3;
# 17.3571       20.2500

/**
  起別名
  as 可以省略
 */
select sum(tage)   as '年齡總和',
       min(tage)   as '最小值',
       max(tage)   as '最大值',
       avg(tage)   as '非 null 的平均值',
       count(tage) as '非 null 的總人數',
       count(*)    as '全部的總人數'
from tab_3;
# 給 欄位 起別名

select sum(t.tage)   as '年齡總和',
       min(t.tage)   as '最小值',
       max(t.tage)   as '最大值',
       avg(t.tage)   as '非 null 的平均值',
       count(t.tage) as '非 null 的總人數',
       count(*)      as '全部的總人數'
from tab_3 as t;
# 給 表 起別名

/**
  like 模糊查詢
 */
select *
from tab_3
where tname like '%1%';
# 查詢名字中含有 1 的人,  % 表示 0-多個字元

select *
from tab_3
where tname like '__1%';
# 查詢名字中第三個字元是1的人  _ 表示1個字元


/**
  分頁查詢 limit n,m
  n為索引(從0開始),m 是獲取的記錄數量
  ⚠️ limit 是 MySQL的方言
 */
select *
from tab_3;

select *
from tab_3
limit 0,4;
# 查詢前四行
select *
from tab_3
limit 4,4;
# 從第 5 行開始,查詢 4 行


/**
  條件查詢 where 條件
  運算子 > >= < <= != = <>
  條件: or , and
  判斷是否是null: is null , is not null
  範圍: x between a and b  [a,b]                  x in (x1,x2,x3)

  ⚠️:不能在 where 後加 聚合函式
 */
select *
from tab_3
where tage != 9
   or tage is null;
# 年齡不等於 9 或者 等於 null
select *
from tab_3
where tage > 20
  and sex = '女';
# 年齡大於20,並且 性別為 女
select *
from tab_3
where tage between 20 and 25;
# 查詢 age 在 20 和 25 之間的人 [20,25]
select *
from tab_3
where tage in (20, 22, 24);
# 查詢 年齡 = 20 或者 22 或者 24 的人

select *
from tab_3
where tage > any_value(20);
# 沒用的東西

/**
  null 轉換
  ifnull(field,value) 如果 filed 為 null 時,按 value 運算
 */
select tage '年齡', tage + 1 '明年的年齡'
from tab_3;
select concat('我叫', tname, '今年', tage, '歲')
from tab_3;
# 任何資料和 null 運算,結果還是 null

select tage '年齡', ifnull(tage, 0) + 1
from tab_3;
select concat('我叫', ifnull(tname, '無名'), '今年', ifnull(tage, 0), '歲')
from tab_3;

select database();
# 獲取當前資料庫