1. 程式人生 > 其它 >MySQL資料庫基礎_表&簡單查詢

MySQL資料庫基礎_表&簡單查詢

  • 建立表

create table IF NOT EXISTS 表名(
    列名 列型別,
    ....
    列名 列型別
);
  • 檢視當前資料庫中所有表名

show tables; 
  • 檢視指定表建立語句

show create table 表名;
  • 查看錶結構

desc 表名;
  • 刪除表

drop table 表名;

簡單查詢

  • 查詢一個欄位

    • select 欄位名 from 表名;
  • 查詢兩個或者多個欄位

    • select 欄位名1,欄位名2 from 表名;
  • 查詢所有欄位

    • 第一種是把所有欄位名都寫上

      select a,b,c,d... from 表名
    • 第二種:可以使用*

      select * from 表名

      注意: 使用*效率低,查詢不建議使用

  • 給查詢起別名

    select 欄位名 as 別名 from 表名

    as關鍵字可以省略,(別名裡面不能有空格,會報錯) 可以使用單引號解決

    欄位是可以參加+-*/運算的

條件查詢

  • 語法格式

    select
        欄位1,欄位2,欄位3...
    from
        表名
    where
        條件
    • = 等於

    • <>或!= 不等於

    • <小於 、 大於>

    • <=小於等於 、 >= 大於等於

    • between.....and..... 兩值之間

    • is null 為null (is not null 不為空)

    • and 並且

    • or 或者

    • in 包含,相當於多個or ,( not in 不在這個範圍中)

      select 
          欄位名1,欄位名2,欄位名3 
      from 
          表名
      where
          id in(3,6,8,9);
  • 模糊查詢

    • like ,支援%和下劃線匹配

      %匹配任意多個字元

      下劃線: 任意一個字元

      找出名字裡含有中的

      select name from 表名 where name like '%中%';

      找出第三個字母是s的

      select name from 表名 where name like
      '__s';

      找出名字裡有"_"的 ,加\轉義

    • select name from 表名 where name like '%\_%'

排序

  • 查詢所有員工薪資,排序 (預設升序)

    select
        name,salary
    from
        表名
    order by
        salary;
  • 指定降序、asc是指定升序

    select
        name,salary
    from
        表名
    order by
        salary desc;
  • 兩個或多個欄位排序

    查詢名字和薪資,薪資升序 ,薪資一樣按照名字升序排列

    select
        name,salary
    from
        表名
    order by
        salary asc,name asc;

    排序總是在最後執行輸出