Add a foregin key to a different table - mysql

I'm trying to add username from my st_accounts column into my table results using mySQL.
st_accounts table
`id` int(11) NOT NULL, //Primary Key
`firstname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`img` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
results table
`score_ID` int(11) NOT NULL, //Primary key
`score` int(20) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I think you want:
create table accounts (
account_id int auto_increment primary key,
. . .
);
create table results (
result_id int auto_increment primary key,
account_id int not null
score int NOT NULL,
score_date date NOT NULL,
constraint fk_results_accounts foreig key (accounts_id) references accounts(account_id)
) ;
Notes:
Declare the primary key explicitly, not in a comment.
My convention is to name the primary key after the name of the table (in singular) with _id after it.
The foreign key has the same name as the primary key -- self documenting.
I made the integer primary keys auto_increment, so the database can assign unique values.

Related

Create two tables customer_data and order_data in SQL in a single execution via PHP

CREATE TABLE IF NOT EXISTS customers_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
INVOICE_ID varchar(50) NOT NULL,
_NAME varchar(255) NOT NULL,
MOBILE bigint(12) NOT NULL,
GSTIN varchar(20) NOT NULL,
_ADDRESS varchar(255) NOT NULL,
EMAIL varchar(255) NOT NULL,
_STATE varchar(50) NOT NULL,
MODE varchar(10) NOT NULL,
_DATE date NOT NULL DEFAULT current_timestamp(),
total_qty int(11) NOT NULL,
total_amount decimal(40,2) NOT NULL,
total_sc_gst decimal(30,2) NOT NULL,
Round_Off float(2,2) NOT NULL,
grand_total decimal(50,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
customer_data created sucessfully.
But there is an error in order_data regarding foreign key. Remember I want to create these two table in a same time.
CREATE TABLE IF NOT EXISTS order_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
cus_id int(20) NOT NULL,
ITEM varchar(255) NOT NULL,
HSN varchar(50) NOT NULL,
QTY int(15) NOT NULL,
RATE decimal(40,2) NOT NULL,
S_C_GST decimal(30,2) NOT NULL,
TOTAL decimal(50,2) NOT NULL,
_DATE timestamp NOT NULL DEFAULT current_timestamp(),
FOREIGN KEY(cus_id) REFERENCES customers_data(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
I got this error.
#1005 - Can't create table test. (errno: 150 "Foreign
key constraint is incorrectly formed")
I think you are using MySQL. You have not used Constraint with Foreign Key. Try the below query.
CREATE TABLE IF NOT EXISTS order_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
cus_id int(20) NOT NULL,
ITEM varchar(255) NOT NULL,
HSN varchar(50) NOT NULL,
QTY int(15) NOT NULL,
RATE decimal(40,2) NOT NULL,
S_C_GST decimal(30,2) NOT NULL,
TOTAL decimal(50,2) NOT NULL,
_DATE timestamp NOT NULL DEFAULT current_timestamp(),
**CONSTRAINT <FK_NAME>** FOREIGN KEY(cus_id) REFERENCES customers_data(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Making the table "at the same time" is not the problem you need to solve, (it's not possible anyway).
You can't make a foreign key if the data type is different from the data type of the referenced column.
order_data.cus_id is an INT column.
customers_data.id is an INT UNSIGNED column.
Change either one or the other data type, so they are the same.

How to convert MySQL query to equivalent Oracle sql Query

I want to convert below MY SQL query to Oracle SQL query, could someone please help ?
Below instructor table is parent entity, and instructor_detail table child entity.
CREATE TABLE `instructor_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`youtube_channel` varchar(128) DEFAULT NULL,
`hobby` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
CREATE TABLE `instructor` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`instructor_detail_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_DETAIL_idx` (`instructor_detail_id`),
CONSTRAINT `FK_DETAIL` FOREIGN KEY (`instructor_detail_id`) REFERENCES `instructor_detail` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
I have tried below but not working
CREATE TABLE instructor (
id numeric(11) NOT NULL PRIMARY KEY,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
email varchar(45) DEFAULT NULL,
instructor_detail_id numeric(10) not null
);
CREATE TABLE instructor_detail (
id NUMERIC(11) NOT NULL PRIMARY KEY,
youtube_channel varchar(128) DEFAULT NULL,
hobby varchar(45) DEFAULT NULL,
CONSTRAINT fk_instructor
FOREIGN KEY (instructor_detail_id)
REFERENCES instructor(instructor_detail_id)
);
error : Error report -
ORA-00904: "INSTRUCTOR_DETAIL_ID": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
Appreciated
Oracle 11 doesn't support auto-generated primary keys, so you need a trigger for that. And there are some different rules on cascading constraints.
But otherwise:
CREATE TABLE instructor_detail (
id int PRIMARY KEY,
youtube_channel varchar2(128) DEFAULT NULL,
hobby varchar2(45) DEFAULT NULL
) ;
CREATE TABLE instructor (
id int NOT NULL PRIMARY KEY,
first_name varchar2(45) DEFAULT NULL,
last_name varchar2(45) DEFAULT NULL,
email varchar2(45) DEFAULT NULL,
instructor_detail_id int,
CONSTRAINT FK_DETAIL FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id)
) ;
CREATE INDEX idx_instructor_instruct_detail_id ON instructor(instructor_detail_id);
Here is a db<>fiddle.

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.

mysql add foreign key constraint error

I have two tables which I'd like to connect with foreign key constraint
For some reason, when I try to do it, it fails and and says: #1215 - Cannot add foreign key constraint
Here is my first table:
CREATE TABLE `zmaneyhayom` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zman_id` varchar(255) NOT NULL,
`tempHour` tinyint(1) NOT NULL,
`tempHourType` varchar(255) NOT NULL,
`tempHourNum` double NOT NULL,
`tempMinutes` tinyint(1) NOT NULL,
`tempMinutesType` varchar(255) NOT NULL,
`tempMinutesNum` double NOT NULL,
`regularMinutes` tinyint(1) NOT NULL,
`regularMinutesNum` double NOT NULL,
`equivalentMinutes` tinyint(1) NOT NULL,
`equivalentMinutesNum` double NOT NULL,
`degreesBelowHorizon` tinyint(1) NOT NULL,
`degreesBelowHorizonNum` double NOT NULL,
`beforeAfter` varchar(6) NOT NULL,
`riseSet` varchar(4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zman_id_2` (`zman_id`),
KEY `zman_id` (`zman_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And this table holds ID and name, which eventually the ID in this table is the name for the previous table (zman_id column):
CREATE TABLE `zmaneyhayomlabels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
This is the code I'm attempting in order to create the constraint:
ALTER TABLE `zmaneyhayom` ADD FOREIGN KEY ( `zman_id` ) REFERENCES `luah_v2`.`zmaneyhayomlabels` (
`id`
) ON DELETE NO ACTION ON UPDATE NO ACTION ;
I have no idea why it's failing :/
What I want is that whenever I go on phpmyadmin and go to the first table, instead of typing some id in zman_id I will have a select box which I can select a name (which is stored in the second table) but the value it will store will be the ID.
they are not same type id is INT and zman_id is varchar.
you can change this
`zman_id` varchar(255) NOT NULL,
to
`zman_id` int(11) NOT NULL,

Duplicate key name 'unique_id'

Here is the sql, however, there is an error says "*#1061 - Duplicate key name 'unique_id'* ", what is the problem.
create table `users`(
uid int(11) auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null,
PRIMARY KEY (`unique_id`),
UNIQUE KEY `uid` (`uid`),
UNIQUE KEY `unique_id` (`unique_id`),
UNIQUE KEY `email` (`email`)
)ENGINE=InnoDB AUTO_INCREMENT=877888 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
remove this line
UNIQUE KEY `unique_id` (`unique_id`),
since unique_id is already Primary Key. and Primary Keys are unique.
full CREATE TABLE statement
create table `users`
(
uid int(11) auto_increment,
unique_id varchar(23) not null,
name varchar(50) not null,
email varchar(100) not null unique, -- specified here
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null,
PRIMARY KEY (`unique_id`),
UNIQUE KEY `uid` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=877888
DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
SQLFiddle Demo