Search code examples
mysqldatabasedb-schema

Db Schema in mysql


Is it possible to create table like this in mysql? If yes please explain me with a sample data in table(what will be value in table when we will do first insert).

Subscriber
------------
SubscriberId: guid() <<pk>>
privateUserIDs string <<fk>>
value1 string
...

User
----
privateUserIDs string <<pk>>
SubscriberId: guid() <<fk>>
value2 string
...

I got this db schema from a Google doc.

Note: Relationship is 1..n

enter image description here


Solution

  • You can create tables in any order within a schema, by turning off the foreign key checks.

    For example, below I create a BannedUsers table with a foreign key on the Users table, without the Users table having been created yet.

    Afterwards, be sure to enable foreign key checks again.

    Example below has been tested on a MySQL 5.5.31 database using the InnoDB engine.

    SET FOREIGN_KEY_CHECKS=0;
    
    CREATE TABLE IF NOT EXISTS `BannedUsers` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `user_id` bigint(10) unsigned NOT NULL,
      `created` datetime NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `user_id` (`user_id`),
      KEY `FK_BannedUsers_Users` (`user_id`),
      CONSTRAINT `FK_BannedUsers_Users` FOREIGN KEY (`user_id`) REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    CREATE TABLE IF NOT EXISTS `Users` (
      `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `email` varchar(254) COLLATE utf8_unicode_ci NOT NULL,
      `username` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
      `firstname` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
      `lastname` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
      `created` datetime NOT NULL,
      PRIMARY KEY (`id`),
      UNIQUE KEY `email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    SET FOREIGN_KEY_CHECKS=1;