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

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.

Related

Add a foregin key to a different table

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.

No auto Increment when MySql Database converted to Postgres database

In Mysql, ID is Auto Increment but when converted to Postgres there is no Auto Increment .
Mysql database
CREATE TABLE IF NOT EXISTS `cities` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`state_id` bigint(20) NOT NULL,
`district_id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(1000) DEFAULT NULL,
`created_by` int(11) NOT NULL,
`modified_by` int(11) DEFAULT NULL,
`is_active` char(1) NOT NULL DEFAULT 'Y',
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `state_id` (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;
After Converted to postgres database
CREATE TABLE cities (
"id" bigint NOT NULL,
state_id bigint NOT NULL,
district_id bigint NOT NULL,
"name" varchar(255) NOT NULL,
description varchar(1000),
created_by int NOT NULL,
modified_by int,
is_active char(1) NOT NULL,
created timestamp,
modified timestamp,
PRIMARY KEY ("id")
);
INSERT INTO cities(state_id, district_id, city_type, name, description,
created_by, modified_by, is_active, created, modified)
VALUES
(1, 1, '', 'Ramtek', null, 1, null, 'Y',
'2015-04-16 10:44:11', '2015-04-16 10:44:11');
You could use bigserial in such cases. It provides an auto increment feature in postgres:
CREATE TABLE cities (
"id" bigserial PRIMARY KEY,
Not Null constraint is provided by default.
Docs : http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-SERIAL

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.

Field not inserting or updating , int type in sql

I am working on magento platform.I face a problem regarding values insertion to specific field: My query run perfect but one specific column not working for any query.I try my best but didn't find why .When i change the column type from int to varchar type it works.This is my table structure.
CREATE TABLE `followupemails_emaillogs` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`schedule_time` datetime DEFAULT NULL,
`sent_time` datetime DEFAULT NULL,
`email_status` varchar(100) DEFAULT NULL,
`client_name` varchar(250) DEFAULT NULL,
`client_email` varchar(250) DEFAULT NULL,
`followupemails_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1.
the "followupemails_id" column not working in insert and update query.This is one update query where record exist that id(29). UPDATE followupemails_emaillogs SET followupemails_id=5 WHERE id =29.
This is insertion query INSERT INTO followupemails_emaillogs SET followupemails_id=4, schedule_time='2013-10-23 08:10:00', email_status='pending', client_name='ayaz ali'.this works fine on fiddle but not on my sqlyog ? what could be the issue.At last i find query that work perfect
.INSERT INTO followupemails_emaillogs (followupemails_id,schedule_time,email_status,client_name,client_email) VALUES (26,'2013-10-23 08:10:00','pending','ayaz ali','mamhmood#yahoo.com');
Can anyone tell me why set query not working but second query works perfect.so that i can accept his answer.Thanks for all your help
Try like this
To Create,
CREATE TABLE followupemails_emaillogs (
id int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
schedule_time datetime DEFAULT NULL,
sent_time datetime DEFAULT NULL,
email_status varchar(100) DEFAULT NULL,
client_name varchar(250) DEFAULT NULL,
client_email varchar(250) DEFAULT NULL,
followupemails_i int(11) DEFAULT NULL,
UNIQUE (id)
)
To Insert,
INSERT INTO followupemails_emaillogs (schedule_time,sent_time,email_status,client_name,client_email,followupemails_i)
VALUES
('2012-05-05','2012-05-06',"sent","sagar","sagar#xxxx.com",2)
the whole query is ok
CREATE TABLE `followupemails_emaillogs` (
`id` int NOT NULL AUTO_INCREMENT,
`schedule_time` datetime DEFAULT NULL,
`sent_time` datetime DEFAULT NULL,
`email_status` varchar(100) DEFAULT NULL,
`client_name` varchar(250) DEFAULT NULL,
`client_email` varchar(250) DEFAULT NULL,
`followupemails_id` int DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1.
but at the last there is dot which is actually error so remove the dot and create the table
latin1.
so remove the dot sign and not null in id filed use this line by default fields are null so don't use default null
id int (8) AUTO_INCREMENT
CREATE TABLE `followupemails_emaillogs` (
`id` int (8) AUTO_INCREMENT,
`schedule_time` datetime DEFAULT NULL,
`sent_time` datetime DEFAULT NULL,
`email_status` varchar(100),
`client_name` varchar(250),
`client_email` varchar(250),
`followupemails_id` int,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1
don't need (11) in the sql query for int operator , This get for length of the nvarchar,varchar datatype column only not a int datatype,So change and write int instead of int(11) and int(8)
Try this query instead of your query
CREATE TABLE `followupemails_emaillogs` (
`id` int NOT NULL AUTO_INCREMENT,
`schedule_time` datetime DEFAULT NULL,
`sent_time` datetime DEFAULT NULL,
`email_status` varchar(100) DEFAULT NULL,
`client_name` varchar(250) DEFAULT NULL,
`client_email` varchar(250) DEFAULT NULL,
`followupemails_id` int DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1.

cannot add second FK : got error can't create table'.jobstatus\#sql-32c_12f2f.frm' (errno:150)

CREATE TABLE `job` (
`jobId` int(11) NOT NULL auto_increment,
`jobcode` varchar(25) default NULL,
`jobname` varchar(255) default NULL,
`location` varchar(255) default NULL,
`budget` int(10) unsigned default NULL,
`year_type` varchar(100) default NULL,
`worklineId` int(11) default NULL,
PRIMARY KEY (`jobId`),
KEY `NewIndex` (`worklineId`),
FOREIGN KEY (`worklineId`) REFERENCES `workline` (`worklineId`)
) TYPE=InnoDB;
CREATE TABLE `subjob` (
`subjobId` int(11) NOT NULL auto_increment,
`subjobcode` varchar(25) default NULL,
`subjobname` varchar(255) default NULL,
`subjobbudget` int(11) unsigned default NULL,
`jobgoal_date` date default '0000-00-00',
`jobId` int(11) default NULL,
PRIMARY KEY (`subjobId`),
KEY `NewIndex` (`jobId`),
FOREIGN KEY (`jobId`) REFERENCES `job` (`jobId`)
) TYPE=InnoDB;
CREATE TABLE `contract` (
`contractId` int(11) NOT NULL auto_increment,
`contractcode` varchar(25) default NULL,
`price` int(11) unsigned default NULL,
`contractprice` int(11) unsigned default NULL,
`company` varchar(50) default NULL,
`signdate` date default '0000-00-00',
`begindate` date default '0000-00-00',
`enddateplan` date default '0000-00-00',
`note` text,
PRIMARY KEY (`contractId`)
) TYPE=InnoDB;
CREATE TABLE `subjob_contract` (
`subjobcontractId` int(11) NOT NULL auto_increment,
`status` varchar(11) default NULL,
`contractId` int(11) default NULL,
`subjobId` int(11) default NULL,
PRIMARY KEY (`subjobcontractId`),
KEY `NewIndex` (`contractId`),
KEY `NewIndex2` (`subjobId`),
FOREIGN KEY (`contractId`) REFERENCES `contract` (`contractId`)
) TYPE=InnoDB
I m using mysql front 3.2 to manage database,I can add first fk but when i add second fk i got an error following this :
sql execution error #1005. response from the database: can't create table'.jobstatus#sql-32c_12f2f.frm' (errno:150). i already define the new index for fk subjobId reference to subjob table what could be the possibility of this error? thank you
Check the datatype and size of the subjobId column on primary table and referenced table. both must be same than it will allow you to create foreign key.
Answer is: You can not refer that column/table which is not created yet. Try to execute tables having foreign keys after the referenced tables.
Obviously you should have consistency in datatypes of foreign key and referenced column as well
Correct Execution Demo. Also You should use Engine=InnoDB instead of Type=InnoDB