简体   繁体   中英

How to Create MySql Partitions without primary key?

I have a database which use sequence number as its primary key. Other than there is a column called "date_time" which can be duplicated.

Now I need to make partitions by using date_time as follows.

ALTER TABLE data
PARTITION BY RANGE (TO_DAYS('date_time')) (
 PARTITION p20220103 VALUES LESS THAN (TO_DAYS('2022-01-04 00:00:00')),
 PARTITION p20220104 VALUES LESS THAN (TO_DAYS('2022-01-05 00:00:00')),
 PARTITION p20220105 VALUES LESS THAN MAXVALUE
);

Since the date_time is not a primary key in data table, I couldn't create partitions.

ERROR 1503 (HY000): A PRIMARY KEY must include all columns in the table's partitioning function (prefixed columns are not considered).

How should I create partitions without adding date_time as a primary key?

You cannot. The rule is simple, stated in https://dev.mysql.com/doc/refman/8.0/en/partitioning-limitations-partitioning-keys-unique-keys.html :

Every unique key on the table must use every column in the table's partitioning expression.

If the table has a primary key or unique key but that key does not include the column(s) in the partitioning expression, then it cannot enforce uniqueness when you insert a new row without checking every partition for duplicates.

The only way around this, to allow a column like your date_time to be the partitioning expression, is to define the table with no primary or unique key .

This has its own hazards. You may need a unique key so you can address rows individually to update or delete them. Also row-based replication becomes very inefficient if your table has no primary key.

This usually means you cannot partition the table by date_time , or even that you cannot partition the table at all. But this isn't always a bad thing. Partitioning doesn't necessarily give a great benefit. Partitioning can even cause more complexity, because you may have queries that would be bound to search every partition anyway.

Partitioning is not a cure-all, and frequently is a liability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM