1. 程式人生 > >mysql筆記三之條件、模糊、範圍查詢

mysql筆記三之條件、模糊、範圍查詢

1.-- 條件查詢 滿足條件 就能夠進入結果集
    -- 比較運算子
        -- >
        -- 查詢大於18歲的資訊
        
        -- <
        -- 查詢小於18歲的資訊

        -- >=
        -- <=
        -- 查詢小於或者等於18歲的資訊

        -- = 而不是 '=='
        -- 查詢年齡為18歲的所有學生的名字
        select name from students where age = 18;
        -- != 或者 <>  實際開發中 最好使用 ! 表示不等於
        -- <> 表示不等於 是一種非常小眾的用法
        select name from students where age <> 18;

    -- 邏輯運算子
        -- and
        -- 18歲以上的女性
        select *  from students where age > 18 and gender = 2;
        -- or
        -- 18以上或者身高超過180(包含)以上
        select * from students where not age > 18 or height >= 180;

        -- not  非
        -- 年齡不是18歲的學生
        select * from students where age != 18;
        select * from students where not age = 18;

        -- 年齡是小於或者等於18 並且是女性
        select * from students where age <= 18 and gender = "女";

select * from students where 1 > 0;

    2.-- 模糊查詢
        -- like 
        -- % 表示任意字元可有可無
        -- 查詢姓名中 以 "小" 開始的名字
        select * from students where name like "小%";
        -- 以 倫 結尾的學生
        select * from students where name like "%倫";

        -- 包含 傑
        select * from students where name like "%傑%"; 


        -- _ 表示任意一個字元
        -- 查詢有2個字的名字
        select * from students where name like "__";

        -- 查詢有3個字的名字
        select * from students where name like "___";

        -- rlike 正則
        -- 查詢以 周開始的姓名
        -- match sub findall 這些只是python中封裝的方法而已
        -- 正則表示式 r""
        select * from students where name rlike "^周.*";
        select * from students where name rlike "^周.*倫$";


        

    3.-- 範圍查詢
        -- in表示在一個非連續的範圍內
        -- 查詢 年齡為18、34的學生
        select * from students where age = 18 or age = 34;
        select * from students where age in (18,34);
        
        
        -- not in 不非連續的範圍之內
        -- 年齡不是 18、34歲的學生的資訊
        select * from students where age not in (18,34);

        -- 年齡不是 18、34歲之間的資訊
        select * from students where age < 18 or age > 34;
        select * from students where not (age >= 18 and age <= 34);
        -- 18 ~ 34
        select * from students where age > 18 and age < 34;


        -- between ... and ...表示在一個連續的範圍內  兩邊都會包含
        -- 查詢 年齡在18到34之間的的資訊
        select * from students where age between 18 and 34;
        
        -- not between ... and ...表示不在一個連續的範圍內
        -- 查詢 年齡不在在18到34之間的的資訊
        select * from students where age not between 18 and 34;
        # 錯誤select * from students where age not (between 18 and 34);

    -- 空判斷 null  不能夠使用比較運算子
        -- 查詢身高為空的資訊
        # 錯誤 select * from students where height = null;
        -- 通過is 來判斷是否為空
        select * from students where height is null;
        -- 查詢身高不為空的學生
        select * from students where height is not null;