[CLOSED] I try to write a query in Sakila Database with MySQL Workbench 8.0 that partitioning the customer table into 5 partitions using the hash type on the customer_id. Check the partitioning information from the INFORMATION_SCHEMA.PARTITIONS table. My code like this:
ALTER TABLE rental PARTITION BY HASH(customer_id) PARTITIONS 5;
When I executed, my action output like
Error Code: 1506. Foreign keys are not yet supported in conjunction with partitioning
I have checked that the customer table just has 3 foreign keys but the customer_id isn't a foreign key in this table. So what did I do wrong? Thanks to read my question.
I suppose you are using the default engine InnoDB, which does not support partitions with foreign key existing. Here is the reference from the official MySQL web:
InnoDB foreign keys and MySQL partitioning are not compatible. Partitioned InnoDB tables cannot have foreign key references, nor can they have columns referenced by foreign keys. InnoDB tables which have or which are referenced by foreign keys cannot be partitioned.
However, if it's an FK table that requires partitioning(not the parent table), we can split it into multiple tables. Note: This is like sharding, which splits a table across different DB servers. But here we do it on the same DB instance.
Suppose we have a
vendorstable and aninvoicestable. Theinvoicestable has a column calledvendor_idwhich references its counterpart in thevendorstable.We would like to split the invoices table into 3 tables:
If we want to populate them based on the vendor_id(splitting key) , we can use a hashing algorithm with the
modoperator:There are several points to note.
The way of using hash is good to query for a constant value of the splitting key (vendor_id), but not ranged values. If the latter is weighted more in querying jobs, consider splitting tables using ranges.
To know which split table to use when querying for a single value of the splitting key, we can apply an mechanism on the application side by calculating which split table to use, then query the corresponding table. Or use a stored procedure which takes the key column value as an in parameter, and determines which table to use. (Using a procedure is not possible for sharding as a procedure cannot cross DB servers) The similar job applies to INSERT statements.
To get the complete set from the split tables, UNION is required.
The parent table (
vendors) should not be split, as an FK table can not references multiple parents.Consider making the splitting number bigger than currently required if the number is going to increase in the future, as relocating can be a tedious job which requires fusing all the split tables into one and do the splitting calculation.