Creating a relationship between tables and creating a foreign key - mysql

How to make relation between these tables?
CREATE TABLE `categories` (
`id` smallint(6) NOT NULL,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`position` smallint(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB;
CREATE TABLE `pm` (
`id` bigint(20) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`user1` bigint(20) NOT NULL,
`user2` bigint(20) NOT NULL,
`message` text NOT NULL,
`timestamp` int(10) NOT NULL,
`user1read` varchar(3) NOT NULL,
`user2read` varchar(3) NOT NULL
) ENGINE=INNODB;
CREATE TABLE `topics` (
`parent` smallint(6) NOT NULL,
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`authorid` int(11) NOT NULL,
`timestamp` int(11) NOT NULL,
`timestamp2` int(11) NOT NULL,
PRIMARY KEY (`id`,`id2`)
) ENGINE=INNODB;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` text NOT NULL,
`signup_date` int(10) NOT NULL
) ENGINE=INNODB;

If a topics has a users as an author,
if you are storing the id value of the users that is the author of the topics in the authorid column,
The "author" relationship is a one-to-many relationship. A topics is related to one (or zero) users. (And a users can be the "author" of zero, one or more topics.)
Here's an example of a foreign key definition to have the database (InnoDB storage engine) enforce the integrity of that relationship:
ALTER TABLE topics
ADD CONSTRAINT FK_topics_users_author
FOREIGN KEY (authorid) REFERENCES users (id)
ON UPDATE CASCADE ON DELETE RESTRICT

Related

Is this relationship OneToMany or ManyToMany?

I have two tables ARTICLE and FAQ ( frequently asked questions ). I'm trying to establish a relationship between these two tables but I'm confused!
What I want to achieve is that article can have many FAQ. So for this should I create a pivot table or just reference a FK in FAQ table?
What I tried but I'm not sure that the below flow is right or not?
Article table:
CREATE TABLE IF NOT EXISTS `article` (
`id` int(11) UNSIGNED NOT NULL,
`title` varchar(255) DEFAULT NULL,
`slug` varchar(255) DEFAULT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`)
);
FAQ Table Schema:
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`)
);
Pivot:
CREATE TABLE IF NOT EXISTS `article_linked_faq` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`faq_id` int(11) DEFAULT NULL,
`order_by` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
This schema will indeed allow an article to have multiple FAQs, but also allows one FAQ to be linked to multiple articles. If that's what you want, great! If not then I'd suggest removing the pivot table and adding article_id into eb_faq.
No, you just need to add foreign key in faq table, it will create the relationship between both tables. There is no need to create a third table
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`articleId` int(11),
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (articleId) REFERENCES article(id)
);

Properly designing an e-commerce database schema where a user can register products only if the user is a vendor

I am creating a simple e-commerce project where a user can sell products and a product can be sold by multiple users. I am attempting to design the database where i have a user table, user roles table, product table and a user_product table. So the user table is self explanatory that stores all users. Now i have user role table that will be defined by client, vendor, and admin. A user can register a product only if he or she is a vendor. So my question is should should i store the id from the user_roles table where he or she is defined as vendor in the user_product table or use the actual id from the user table.
So currently i have my database as:
create table `user` (
`id` bigint(20) not null auto_increment,
`firstname` varchar(100) not null,
`lastname` varchar(100) not null,
`email` varchar(255) not null,
`is_deleted` bit(1) not null default b'0',
primary key(`id`),
unique key(`email`)
);
create table `product`(
`id` bigint(20) not null auto_increment,
`name` varchar(255) not null,
`sku` varchar(255) not null,
primary key(`id`),
unique key(`sku`)
);
create table `roles`(
`id` bigint(20) not null auto_increment,
`name` varchar(100) not null
primary key(`id`)
);
create table `user_roles` (
`id` bigint(20) not null auto_increment,
`role_id` bigint(20) not null,
`user_id` bigint(20) not null,
primary key(`id`),
foreign key(`role_id`) references `role`(`id`),
foreign key(`user`) references `user`(`id`)
);
create table `user_product`(
`id` bigint(20) not null auto_increment,
`vendor_id` bigint(20) not null,
`product_id` bigint(20) not null,
`description` text not null,
`price` decimal(5,2) not null,
primary key(`id`),
foreign key(`user_id`) references `user`(`id`),
foreign key(`vendor_id`) references `user_roles`(`id`)
);

Mysql error 1215 - Cannot add foreign key constraint

Created these two tables successfully
First table
CREATE TABLE IF NOT EXISTS `lawncare_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`UserType` varchar(30) NOT NULL,
`UserName` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL,
`Status` BOOLEAN NOT NULL DEFAULT '0',
`QuestionID` int(11) DEFAULT NULL,
`QuestionAnswer` text DEFAULT NULL,
`Params` text NOT NULL,
`Address` text NOT NULL,
`Country` varchar(300) NOT NULL,
`State` varchar(300) NOT NULL,
`City` varchar(300) NOT NULL,
`ContactNo` double DEFAULT NULL,
`Activation` BOOLEAN NOT NULL DEFAULT '0',
`ActivatedOn` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Second table
CREATE TABLE IF NOT EXISTS `lawncare_customer` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`ContactNo` varchar(20) NOT NULL,
`Address` varchar(255) NOT NULL,
`Params` text NOT NULL,
`Province` varchar(255) NOT NULL,
`ZipCode` varchar(255) NOT NULL,
`Status` Boolean NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
`ModifiedOn` date DEFAULT NULL
) ENGINE =InnoDB DEFAULT CHARSET=latin1;
But while creating third table as
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL
FOREIGN KEY (SendTo, SendToUser, SendToEmail)
REFERENCES lawncare_user(ID, UserName, Email)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer, CustomerUser, CustomerEmail)
REFERENCES lawncare_customer(ID, FirstName,Email)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1
I get #1215 - Cannot add foreign key constraint , error in mysql tried adding foreign keys after creating table but it still gives the same error. I don't know what I'm doing wrong here.
First of all Check whether you have applied indexes on the keys.
As per your code their is no point in referencing id,UserName and Email.
Only id is enough for referencing.
Check the following code
CREATE TABLE IF NOT EXISTS `lawncare_message` (
`ID` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`Reason` int(5) NOT NULL,
`Subject` text NOT NULL,
`Description` text NOT NULL,
`Customer` int(11) NOT NULL,
`CustomerUser` varchar(255) NOT NULL,
`CustomerEmail` varchar(255) NOT NULL,
`SendTo` int(11) NOT NULL,
`SendToUser` varchar(255) NOT NULL,
`SendToEmail` varchar(255) NOT NULL,
`Status` int(5) NOT NULL DEFAULT '0',
`AddedBy` int(11) NOT NULL,
`AddedOn` date NOT NULL,
FOREIGN KEY (SendTo)
REFERENCES lawncare_user(ID)
ON UPDATE CASCADE ,
FOREIGN KEY (Customer)
REFERENCES lawncare_customer(ID)
ON UPDATE CASCADE
) ENGINE =InnoDB DEFAULT CHARSET=latin1

error 105 mysql FOREIGN KEYS

I am trying to create database table and get them connected by mysql FOREIGN KEYS. I have ensured that my data types are identical. I also ensure that my tables are made before added the FK. Any advice would be greatly appreciated.
CREATE TABLE IF NOT EXISTS `af_feeds` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`hash` char(255) NOT NULL,
`seed_id` int(64) NOT NULL,
`category_id` int(64) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text,
`content` longtext,
`publishing_date` varchar(255) NOT NULL,
`link` text NOT NULL,
`status` int(1) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`),
FOREIGN KEY (`seed_id`) REFERENCES `af_seeds`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (`category_id`) REFERENCES `af_categories`(`id`)
ON UPDATE CASCADE
ON DELETE CASCADE
MySQL said:
1005 - Can't create table 'estafeed_rss.af_feeds' (errno: 150) (Details…)
--
-- Table structure for table `af_categories`
--
CREATE TABLE IF NOT EXISTS `af_categories` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`icon` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`status` int(1) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
-- --------------------------------------------------------
--
-- Table structure for table `af_seeds`
--
CREATE TABLE IF NOT EXISTS `af_seeds` (
`id` int(64) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`link` varchar(255) NOT NULL,
`category_id` int(64) NOT NULL,
`loading_times` int(64) NOT NULL,
`status` int(1) NOT NULL,
`loading_each` int(64) NOT NULL,
`last_loading` int(64) NOT NULL,
`create_date` int(64) NOT NULL,
`update_date` int(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `url` (`link`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;

Creating a MySQL Table but get error

I get
errnno 150: InnoDB Documentation
Supports transactions, row-level locking, and foreign keys
Here is the SQL:
-- Table structure for table `Serving_Info`
--
CREATE TABLE IF NOT EXISTS `Serving_Info` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`Food_Value` varchar(40) NOT NULL,
`Food_name` varchar(40) NOT NULL,
`Served_On` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`Oncall` varchar(128) NOT NULL,
Foreign key(`Oncall`) REFERENCES `employees`(`name`),
Foreign key(`Food_name`) REFERENCES `Foods`(`Food_name`),
PRIMARY KEY (`Oncall`,`Food_name`, `Served_On`)
);
Any idea what is causing the error? I have tried making id part of the primary key but that isn't solving the problem either.
Here are the statements for the tables I am referencing:
CREATE TABLE IF NOT EXISTS `employees` (
`id_user` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`email` varchar(64) NOT NULL,
`phone_number` varchar(16) NOT NULL,
`username` varchar(16) NOT NULL,
`password` varchar(32) NOT NULL,
`confirmcode` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id_user`)
);
--
-- Table structure for table `Foods`
--
CREATE TABLE IF NOT EXISTS `Foods` (
`Food_name` varchar(40) NOT NULL,
`CostPerRefill` double NOT NULL,
PRIMARY KEY (`Food_name`)
);
I just tried the below but I get the same error:
--
-- Table structure for table `Serving_Info`
--
CREATE TABLE IF NOT EXISTS `Serving_Info` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`Food_Value` varchar(40) NOT NULL,
`Food_name` varchar(40) NOT NULL,
`Served_On` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`Oncall` varchar(128),
Foreign key(`Oncall`) REFERENCES `employees`(`name`),
Foreign key(`Food_name`) REFERENCES `Foods`(`Food_name`),
PRIMARY KEY (`id`),
UNIQUE (`Oncall`,`Food_name`, `Served_On`)
);
Your problem is that the reference is to employees.name rather than employees.id_user. Try this:
CREATE TABLE IF NOT EXISTS `Serving_Info` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`Food_Value` varchar(40) NOT NULL,
`Food_name` varchar(40) NOT NULL,
`Served_On` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`Oncall` int,
PRIMARY KEY (`id`),
Foreign key(`Oncall`) REFERENCES `employees`(`id_user`),
Foreign key(`Food_name`) REFERENCES `Foods`(`Food_name`),
UNIQUE (`Oncall`,`Food_name`, `Served_On`)
);
Otherwise, change the employees table so name has an index:
CREATE TABLE IF NOT EXISTS `employees` (
`id_user` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL ,
`email` varchar(64) NOT NULL,
`phone_number` varchar(16) NOT NULL,
`username` varchar(16) NOT NULL,
`password` varchar(32) NOT NULL,
`confirmcode` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id_user`),
KEY (name)
);
In practice, if you are going to use name this way, you should probably make that unique rather than just key.