MySQL insert into different databases tables based on PK value

insertMySQLsharding

Lets assume i have two databases, both having a table 'user_feedback', sharding data between the two databases. My goal is to insert all records where Primary key Id%2=0 goes to db1.user_feedback, and Id%2=1 goes to db2.user_feedback.

Is there a condition in the INSERT statement that can allow me to do this? How can i achieve simply achieve this, both if the two databases are located on the same MySQL server, and when they both reside on a different MySQL server?

** UPDATE **
Ok, what i am trying to achieve is to have several tables in the same MySQL server to shard data and limit one table from becoming too big, hence slowing up queries on this table. The table is expected to grow very large (billion records) with heavy writes. That is the reason we have decided to resort to sharding. The table does not currently exist, but we want to create this shard solution in advance before we hit production with this table.

Best Answer

I am extremely dubious that you have the problem you describe, but here goes:

CREATE TEMPORARY TABLE t (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    ...   (the rest of the columns)
    );

INSERT INTO t
    SELECT * FROM source;

INSERT INTO db1.x  SELECT ... FROM t WHERE id % 2 = 0;
INSERT INTO db2.x  SELECT ... FROM t WHERE id % 2 = 1;

If the data is coming from clients that are feeding the data in fast and furious, then I recommend ping-ponging between two temp tables, not between even/odd. The clients will INSERT into one temp table while a separate task is copying the other temp table into one of the two 'real' tables. Then that task will TRUNCATE the table it copied, then RENAME TABLE to atomically swap the temp tables.

I discuss that in more detail in http://mysql.rjweb.org/doc.php/staging_table