1. 程式人生 > >MySQL基礎操作案例

MySQL基礎操作案例

綜述:兩張表,一張顧客資訊表customers,一張訂單表orders

建立一張顧客資訊表customers,欄位要求如下:
c_id 型別為整型,設定為主鍵,並設定為自增長屬性
c_name 字元型別,變長,寬度為20
c_age 微小整型,取值範圍為0~255(無符號)
c_sex 列舉型別,要求只能在('M','F')中選擇一個值
c_city 字元型別,變長,寬度為20
c_salary 浮點型別,要求整數部分最大為10位,小數部分為2位

    create table customers(
    c_id int primary key auto_increment,
    c_name varchar(20),
    c_age tinyint unsigned,
    c_sex enum("M","F"),
    c_city varchar(20),
    c_salary float(12,2)
    );

在表中任意插入3條記錄,c_name為"Zhangsan","Lisi","Wangwu", c_city儘量 寫"Beijing","Shanghai" ......

    insert into customers values
    (1,"Zhangsan",25,"M","Beijing",8000),
    (2,"Lisi",30,"F","Shanghai",10000),
    (3,"Wangwu",27,"M","Shenzhen",3000);

建立一張訂單表orders,欄位要求如下:

o_id 整型
o_name 字元型別,變長,寬度為30
o_price 浮點型別,整數最大為10位,小數部分為2位
設定此表中的o_id欄位為customers表中c_id欄位的外來鍵,更新刪除同步

    create table orders(
    o_id int,
    o_name varchar(30),
    o_price float(12,2),
    foreign key(o_id) references customers(c_id)
    on delete cascade
    on update cascade
    );

在表中任意插入5條記錄(注意外來鍵限制)

o_name分別為"iphone","ipad","iwatch","mate9","r11",其他資訊自己定

    insert into orders values
    (1,"iphone",5288),
    (1,"ipad",3299),
    (3,"mate9",3688),
    (2,"iwatch",2222),
    (2,"r11",4400);

返回customers表中,工資大於4000元,或者年齡小於29歲,滿足這樣條件的前2條記錄

  select * from customers where c_salary > 4000 or c_age < 29 limit 2;

把customers表中,年齡大於等於25歲,並且地址是北京或者上海,這樣的人的工資上調15%

  update customers set c_salary=c_salary*1.15 where c_age >= 25 and c_city in ("Beijing","Shanghai");

把customers表中,城市為北京的顧客,按照工資降序排列,並且只返回結果中的第一條記錄

  select * from customers where c_city="Beijing" order by c_salary desc limit 1;    

選擇工資c_salary最少的顧客的資訊

  select * from customers 
  where c_salary = (select min(c_salary) from customers);

找到工資大於5000的顧客都買過哪些產品的記錄明細

  select * from orders where o_id in (select c_id from customers where c_salary > 5000);
                

刪除外來鍵限制

  1、show create table orders;
  2、alter table orders drop foreign key orders_ibfk_1;
            

刪除customers主鍵限制

  1、刪除自增長屬性
    alter table customers modify c_id int;
  2、刪除主鍵限制
    alter table customers drop primary key;

增加customers主鍵限制c_id

  alter table customers add primary key(c_id);