1. 程式人生 > >資料庫-事務-樂觀鎖-調優

資料庫-事務-樂觀鎖-調優

關係型資料庫

基於關係代數理論

缺點:表結構不直觀,實現複雜,速度慢
優點:健壯性高,社群龐大

示例:
    product表
            productId    productName    categoryId    price
        1    4            toyota        2            100000
        2    3            porsche        2            1000000
        3    2            addidas        1            500
        4    1            nike        null        600

    category
            categoryId    categoryName
        1    2            automobile
        2    1             shoe


    select * from 'product' join 'category'    沒有條件會發生笛卡爾積

    select * from 'product'    p join 'category' c 
    on p.'categoryId' = c.'categoryId'

    左外連線,左表都有,
    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'

    右外連線
    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'

    select * from 'product'    p left join 'category' c 
    on p.'categoryId' = c.'categoryId'
    group by p.'categoryId'

    select * from 'producet' p left join (
        select p.'categoryId', 'categoryName', MIN(p.'price') as min_price from 'product' p left join 'category' c
        on p.'categoryId' = c.'categoryId'
        group by p.'categoryId','categoryName') as cat_min
    on p.'categoryId' = cat_min.categoryId
    where p.'price' = cat_min.price

事務
    ACID
        Atomicity
        Consistency
        Isolation
        Durability

    事務的隔離級別
        Read uncommitted
        Read Committed
        Repeatable Reads
        Serializable

    product表
            productId    productName    categoryId    price         count
        1    4            toyota        2            100000
        2    3            porsche        2            1000000
        3    2            addidas        1            500         50
        4    1            nike        null        600

    set session transaction isolation level read committed;
    begin;
    set autocommit = 0;
    select count from 'product' where 'productId'=2;

    update 'product' set 'count'=49 where 'productId' = 2;

    select count from 'product' where 'productId'=2 for update;    //會被鎖掉,事務做完才會執行
    commit;

 

    update 'product' where set count = count-1 where 'productId' = 2;


樂觀鎖

    演示:
        讀取資料,記錄Timestamp
        修改資料
        檢查和提交資料

    select count from 'product' where 'productId' = 2;
    update 'product' set 'count' = 46 where 'productId' =2 and 'count'=47;    //and後這個就是樂觀鎖,設定46之前需要讀到count為47


程式調優:
    改善資料訪問方式以提升快取命中率
    利用資料庫連線池替代直接的資料庫訪問
    使用迭代替代遞迴
    合併多個遠端呼叫批量傳送
    共享冗餘資料提高訪問效率