MyCAT操做MySQL示例之E-R表

接着上一篇繼續.....數據庫

  E-R 關係的數據分片策略,子表的記錄與所關聯的父表記錄存放在同一個數據分片上,即子表依賴於父表,經過表分組(Table Group)保證數據 Join 不會跨庫操做。測試

表分組(Table Group)是解決跨分片數據 join 的一種很好的思路,也是數據切分規劃的重要一條規則。spa

  MyCAT的官方文檔是經過customer這張表來說解E-R分片策略的,現記錄以下:
3d

1.在schema.xml配置文件中schema標籤中配置customer table 的分庫策略xml

 <!-- ER表配置示例-->
 <table name="customer" primaryKey="ID" dataNode="dn1,dn2,dn3" rule="sharding-by-intfile">
   <childTable name="orders" primaryKey="ID" joinKey="customer_id" parentKey="id">
     <childTable name="order_items" joinKey="order_id" parentKey="id" /> </childTable>
   <childTable name="customer_addr" primaryKey="ID" joinKey="customer_id" parentKey="id" />
 </table>
blog

  配置說明: table標籤代表這是配置表信息; name = "customer" 說明這張表的名稱叫customer, id 是 主鍵, 表分佈在dn1,dn2,dn3這三個數據庫中, 表的分片策略是sharding-by-intfile.rem

  childTable代表子表信息, 此示例中說明customer關聯了兩張子表,分別是orders,customer_addr;咱們以orders表爲例說明.文檔

  orders表的主鍵是id,它經過joinKey關聯父表的parentKey.本例中orders表就是以customer_id去關聯customer表的id.也就是說,當customer表中id = 1 在dn1時,那麼orders表中customer_id = 1這條數據也會在dn1這個數據庫. 這樣設置就避免了跨庫join,提升了查詢效率.it

  一樣的,order_items表關聯的父表是orders. 原理同樣.table

2. 測試

  建立customer表:

    customer(id int not null primary key,name varchar(100),company_id int not null,sharding_id int not null);

  插入數據:

    insert into customer (id,name,company_id,sharding_id )values(1,'wang',1,10000);  
    insert into customer (id,name,company_id,sharding_id )values(2,'xue',2,10010);
    insert into customer (id,name,company_id,sharding_id )values(3,'feng',3,10000);
    insert into customer (id,name,company_id,sharding_id )values(4,'test',4,10010);
    insert into customer (id,name,company_id,sharding_id )values(5,'admin',5,10010);

  建立orders表:

    create table orders (id int not null primary key ,customer_id int not null,sataus int ,note varchar(100) );

  插入數據:

    insert into orders(id,customer_id) values(1,1);
       insert into orders(id,customer_id) values(2,2);

    insert into orders(id,customer_id,sataus,note) values(3,4,2,'xxxx');

    insert into orders(id,customer_id,sataus,note) values(4,5,2,'xxxx');

  建立order_items表:

    create table order_items (id int not null primary key ,order_id int not null,remark varchar(100) );

  插入數據:

     insert into order_items(id,order_id,remark) VALUES (1,1,'1mark');
     insert into order_items(id,order_id,remark) VALUES (2,2,'2mark');
        insert into order_items(id,order_id,remark) VALUES (3,3,'3mark');
        insert into order_items(id,order_id,remark) VALUES (4,4,'4mark');

觀察結果:

 

  

 

 

 驗證完畢!!!

相關文章
相關標籤/搜索