Question

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

Was it helpful?

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;

OTHER TIPS

It is not possible. Reason is simple

If you first create user table then while describing it's schema table subscriber must exist since you will be requiring reference of PK of subscriber table in user table to create FK.

Similarly, if you create subscriber table first you will require user table schema which is again not possible due to above reason.

Moreover, if somehow you define two tables you may end up with highly inconsistent db in future since deletion of row from 1 table would render the data in other inconsistent due to FK constraints.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top