This is my first post and I can't seem to find the answer anywhere....
I have a database that has multiple companies,each company has multiple locations.
I'm running into problems trying to define the contacts. Some contacts need to be global and available
at any location....some contacts only need to exist for one location. In the contact_info table below
we specify the visibility of the contact (company or location). However the location needs to choose its primary contact.
That leaves a FK from contact -> location and from location -> contact.
I know there is another table involved but I can't seem to conceptualize it.
CREATE TABLE `company_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`));
CREATE TABLE `location_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_info` INT NOT NULL DEFAULT -1,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`primary_contact_id` INT NOT NULL DEFAULT -1,
PRIMARY KEY(`id`),
UNIQUE KEY(`company_id`,`name`),
FOREIGN KEY (company_id) REFERENCES company_info(id)
FOREIGN KEY (primary_contact_id) REFERENCES contact_info(id));
CREATE TABLE `contact_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_id` INT
`location_id` INT,
`type` ENUM('Company','Location') NOT NULL DEFAULT 'Company',
`first_name` VARCHAR(50) NOT NULL DEFAULT '',
`last_name` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
UNIQUE KEY(`id`,`company_id`,`location_id`),
FOREIGN KEY (location_id) REFERENCES location_info(id),
FOREIGN KEY (company_id) REFERENCES company_info(id)
The most effective way would be splitting it up so that there's a table for your companies, a table with your users, and a table solely for the purpose of storing all connections (i.e. EntryID, UserID, CompanyID). This way you'll be able to easily load them afterwards.
Related
This question already has answers here:
MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'
(9 answers)
Closed 6 years ago.
I am building a CRUD app in PHP & MySql. It uses two tables, called users and medical_records:
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(1024) NOT NULL,
`validation_code` text NOT NULL,
`active` tinyint(1) NOT NULL,
`telefon` varchar(255) DEFAULT NULL,
`oras` varchar(255) DEFAULT NULL,
`adresa` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE medical_records (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`fo` VARCHAR(255),
`condition` VARCHAR(255),
`transfer` VARCHAR(255),
`memo` text(1024),
`body_temperature` VARCHAR(255),
PRIMARY KEY (`id`),
CONSTRAINT FK_medical_records_1
FOREIGN KEY (user_id) REFERENCES users(id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
The "business logic" of these tables is: every user has one (only one) medical record.
I used and tested the application when it only had the users table. Register and login worked fine, so I conclude that the problem's source can't be the application's (PHP) code.
I later doped the users table and added the 2 fresh tables the application now uses (users and medical_records).
At this moment whenever I try to register a second user, I get the error:
QUERY FAILED: Duplicate entry '0' for key 'PRIMARY'
This happens despite the fact that both tables have auto incremented primary keys. What could be the explanation of that?
the id in the users table is not set to AUTO_INCREMENT. that's why this happens.
I've tried many different ways to create table with a foreign key and trying to insert into phpMyAdmin. However, it just not working as I was expected.
Here are what I've so far:
CREATE TABLE user (
user_id BIGINT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(50) NOT NULL,
user_password VARCHAR(50) NOT NULL);
This works perfectly fine. However, if I try to add a table with a foreign key thus, it refuses to create:
CREATE TABLE article (
article_id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
article_title VARCHAR(100) NOT NULL,
article_content VARCHAR(1000) NOT NULL,
user_id INT(10) NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (user_id));
This would not work as expected and would not add the table to the MySQL database. I get this error:
Cannot add foreign key constraint
How can I fix it?
We discovered in the comments that if a primary key is defined thus:
user_id BIGINT(10) UNSIGNED
then a foreign key like this will not work, since it needs to match on signedness (and I think type too):
user_id INT(10) NOT NULL
This works fine:
user_id BIGINT(10) UNSIGNED NOT NULL
Here's a Fiddle to demonstrate it working.
I am trying to write a PHP script to create 2 tables in the same database, which should be linked through a 1 (table category) to many (table page) relationship. Hence, primary key 'category_id' from the 'category' table should be the foreign key in the table 'page'.
The table 'category' creates successfully without problems:
$sql="CREATE TABLE category(
category_id SMALLINT NOT NULL AUTO_INCREMENT,
category VARCHAR(30) NOT NULL,
PRIMARY KEY (category_id),
UNIQUE (category)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
Then I am trying to create the second table 'page':
$sql="CREATE TABLE page(
page_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
category_id SMALLINT UNSIGNED NOT NULL,
title VARCHAR(100) NOT NULL,
description TINYTEXT NOT NULL,
content LONGTEXT NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (page_id),
FOREIGN KEY (category_id) REFERENCES category (category_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
And I get the following error:
Error creating table: Cannot add foreign key constraint
Could you please tell me what's wrong with my code? Thanks a lot in advance.
Per the MySql manual at http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html:
Corresponding columns in the foreign key and the referenced key must have similar data types.
The size and sign of integer types must be the same.
The problem is that you're specifying your foreign key as UNSIGNED, while your primary is not. Make sure that your foreign key matches the specifications of its parent.
From the MySQL Using FOREIGN KEY Constraints documentation:
Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same.
In your page table, the category_id is SMALLINT UNSIGNED, but in category it's just SMALLINT. They need to be exactly the same.
The columns used for your foreign key must have a matching specification. Here you have one category_id column signed, while the other is unsigned. Change one.
you problem is the UNSIGNED in category_id.
try to remove it
try
$sql="CREATE TABLE page(
page_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
category_id SMALLINT NOT NULL,
title VARCHAR(100) NOT NULL,
description TINYTEXT NOT NULL,
content LONGTEXT NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (page_id),
FOREIGN KEY (page.category_id) REFERENCES category (category.category_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
I have a project coming up for doing Admin functions so my question is this. I will try and be clear as possible.
I will have one SUPER-USER who updates all information for other regular-users/people(being our clients).
The clients/regular-users when they log in will only see their info and download files uploaded by SUPER-USER and not see for regular-users.
So if you are Client:#01 you will see the dashboard (welcome page) and your info. Can anyone suggest possible database designs for this.
How to use left/right sql-joins between the user and files table?
UPDATE
I have a users table as well as a company table that the user belongs to. So essentially I want something like this::
$sql = select everything in the users table where the username and pass = to the given form, then left or right join that username to the company that he belong to.
Then they will see their information. if logged in successfully. Because user #01 belongs to company #03 /#01 etc...
USER TABLE looks so
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(50) NOT NULL,
'lname` varchar(100) NOT NULL,
`username` varchar(50) ,
`password` varchar(100) ,
`company` varchar(50) // the company name that ther user belongs to
PRIMARY KEY (`id`)
COMPANY table
'id' int(11) not null auto_increment,
'user_id' int(11) //This is to tie the users to this table
'description' varchar(text),
'filename' varchar(25) not null,
'mimetype' varchar (25) not null
PRIMARY KEY ('id')
Well, it depends on how simple or complex you want to go. with something like this I usually will keep it relatively simple and have a main user database (for all users) example:
CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(255) NOT NULL AUTO_INCREMENT,
`user_name` varchar(50) NOT NULL,
`user_pass` varchar(100) NOT NULL,
`user_permissions` tinyint(1) NOT NULL DEFAULT '0',
`active` tinyint(1) NOT NULL DEFAULT '1',
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MYISAM;
Then I would have possible a second table of permissions depending on how many permissions I was going to have. If all you are going to have is users and super users then you could probably just assign users a value of 0 and then super user a value of 1.
Then in your PHP script it would treat the users different based on their "user_permissions" value.
Now if you are intending to have lots of different levels of permissions then I would definitely create at least one more table to define permissions example:
CREATE TABLE IF NOT EXISTS `permission` (
`permission_id` int(255) NOT NULL AUTO_INCREMENT,
`permission_name` varchar(100) NOT NULL,
`permission_value` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MYISAM;
Then in the permissions table you could assign all sorts of different permissions... read, write, publish, admin, regular user, super user etc.
This is just a very simple starting point. hope that helps.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`status` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
Please explain me what is doing UNIQUE KEY 'username' (username') statement in the example above and why ('username') is written once again?
The UNIQUE_KEY line is creating a unique index called 'username' on the column 'username'. A unique index allows only a single record to have a specific value. This is useful on rows like usernames because it prevents two users from being created with the same username.
However, I think you would get an error if you ran this because you have not defined a column called username.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`status` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
This is simply the format MySQL's CREATE TABLE syntax expects. If you look at the syntax in detail, you'll see...
UNIQUE [INDEX|KEY]
[index_name] [index_type] (index_col_name,...)
[index_option] ...
In other words, you're using an index_name of "username" which uses the "username" field/column. This might seem odd, but if you were using a compound key, you'd might have a definition something like...
UNIQUE KEY duplicate_lock (user_email, user_name)
...so you'd have different index name and column portions of the definition.