How to add foreign key in table using existing column, without losing data? - mysql

I have a table in which I need to add foreign key on an existing column. Following is create table:
CREATE TABLE `itemtx` (
`itemTxid` int(11) NOT NULL AUTO_INCREMENT,
`itemcode` varchar(1) NOT NULL,
`weight` decimal(7,3) DEFAULT NULL,
`txtype` varchar(10) DEFAULT 'Pickup',
`tripstopid` int(11) NOT NULL,
`barcode` varchar(25) DEFAULT NULL,
`bagcount` int(11) DEFAULT '1',
PRIMARY KEY (`itemTxid`)
) ENGINE=InnoDB AUTO_INCREMENT=33524 DEFAULT CHARSET=latin1
I need to add foreign key on tripstopid column. I cannot drop or empty table as it contains data. Following is the referenced table:
CREATE TABLE `tripstop` (
`tripstopid` int(11) NOT NULL AUTO_INCREMENT,
`tripid` int(11) DEFAULT NULL,
`locationName` varchar(100) DEFAULT NULL,
`userName` varchar(100) DEFAULT NULL,
`locationid` int(11) DEFAULT NULL,
`datetime` varchar(20) DEFAULT NULL,
`createts` varchar(20) DEFAULT NULL,
`latitude` double DEFAULT NULL,
`longitude` double DEFAULT NULL,
`userid` int(11) DEFAULT NULL,
`tid` int(11) DEFAULT NULL,
PRIMARY KEY (`tripstopid`)
) ENGINE=InnoDB AUTO_INCREMENT=4691 DEFAULT CHARSET=latin1
How can I do this without losing my data?

You can achieve this by following:
ALTER TABLE itemtx
ADD FOREIGN KEY (tripstopid) REFERENCES tripstop(tripstopid);
Verified by creating tables, inserting data in them and then updating table for foreign key, previously entered data is not lost.

Related

Cant create a relation in mysql - Error creating foreign key on id_produk (check data types)

here is my table :
CREATE TABLE `pesanan` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ref_number` varchar(50) NOT NULL DEFAULT '',
`id_produk` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`qty` int(11) NOT NULL,
`total` varchar(50) NOT NULL DEFAULT '',
`tanggal` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
i want to create a relation of id_produk to table produk.id and id_user to user.id, here is the other table :
CREATE TABLE `produk` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_kategori` int(11) NOT NULL,
`status` varchar(10) NOT NULL DEFAULT '',
`slug` varchar(100) NOT NULL DEFAULT '',
`judul` varchar(100) NOT NULL DEFAULT '',
`harga` varchar(10) DEFAULT '',
`target` int(11) DEFAULT NULL,
`desc` text,
`cover` varchar(100) DEFAULT NULL,
`tanggal` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=latin1;
and user table
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`suspended` int(11) DEFAULT NULL,
`level` varchar(11) DEFAULT NULL,
`nama` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`alamat` text,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1;
when i try to relation it , it give me this error :
Error creating foreign key on id_produk (check data types)
The columns should have the exact same data type in both tables. In your case in the "produk" and "user" tables they are unsigned, which means they go from 0 to 4294967295 but in the "pesanan" table they are signed which means they go from -2147483648 to 2147483647. See more here.
If the server allowed you to create such foreign keys, it would possibly create situations where, for example, a user is added with and ID of 2147483648 that cannot ever be referenced in the "pesanan" table.
You should change the "id_produk" and "id_user" columns in the "pesanan" table to be unsigned.

MySQL Error Number 150 when creating Table with Foreign Key

I am having an issue creating a new table in my database. I've seen that the error code it is returning is to do with Foreign Key constraints.
I checked to ensure that the data type of the foreign key in the new table matched the data type of the primary key in the other table. They are both int(11).
However I am still getting an error. Am I missing something? This is my SQL script for creating the new table:
CREATE TABLE `regular_features` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200) DEFAULT NULL,
`day` VARCHAR(200) DEFAULT NULL,
`description` TEXT DEFAULT NULL,
`programme_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`programme_id`) REFERENCES directoryprogramme(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This is the original table containing the primary key:
CREATE TABLE `directoryprogramme` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(250) NOT NULL,
`broadcast_time` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`days` VARCHAR(150) NOT NULL,
`contributors` VARCHAR(250) NOT NULL,
`directorycompany_id` INT(11) NOT NULL,
`directorycontact_id` VARCHAR(250) NOT NULL,
`facebook_link` VARCHAR(250) DEFAULT NULL,
`twitter_link` VARCHAR(250) DEFAULT NULL,
`wikipedia_link` VARCHAR(250) DEFAULT NULL,
`web` VARCHAR(250) DEFAULT NULL,
`imageextension` VARCHAR(10) DEFAULT NULL,
`type` VARCHAR(20) NOT NULL DEFAULT 'other',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=1161 DEFAULT CHARSET=utf8;
The Foreign Key will be the id of directoryprogramme
The problem is the last line of your create statement:
ENGINE=INNODB DEFAULT CHARSET=utf8;
You mix MYISAM in ald table with INNODB in your new table.
That doesn't work.
Chnage the engine in your new table to MYISAM and it works.

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

MySQL count from one table while joining another

I don't know if it's just been a long day or what, but I cannot figure out the query that I need to run here. We have two tables - One for leads generated and one for reports. The leads table has basic lead info, along with the Source (Campaign) of the lead. However, we need to know the number of leads that an ACCOUNT has received within a date range. Here is the relevant table structure:
client_leads:
id
source
date
client_reports:
account
campaign
date
The 'source' column contains the same values as the 'campaign' column. So, how would I achieve the following:
Say there are 10 leads in the leads table, each with the campaign that generated the lead. There are 10 accounts in the reports table, each with hundreds of campaigns. I need to list each account and how many leads it has in the leads table.
I just can't get the logic straight in my head. I've tried everything that I can think of and it's just not working out for me. If you need further explanation, let me know. I'm trying to describe the problem to the best of my ability.
Edit:
CREATE TABLE `client_leads` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`site_id` int(10) DEFAULT NULL,
`ip` varchar(255) DEFAULT NULL,
`source` varchar(255) DEFAULT NULL,
`kw` varchar(255) DEFAULT NULL,
`adgroup` varchar(255) DEFAULT NULL,
`time` time DEFAULT NULL,
`date` date DEFAULT NULL,
`dayweek` varchar(255) DEFAULT NULL,
`first_name` varchar(255) DEFAULT NULL,
`last_name` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`postal_code` char(5) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`preferred_phone` varchar(10) DEFAULT NULL,
`alternate_phone` varchar(10) DEFAULT NULL,
`level_of_education` varchar(255) DEFAULT NULL,
`program_of_interest` varchar(255) DEFAULT NULL,
`organic` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `site_id` (`site_id`),
KEY `date_indeces` (`time`,`date`,`dayweek`) USING BTREE,
CONSTRAINT `site_id` FOREIGN KEY (`site_id`) REFERENCES `client_sites` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8
CREATE TABLE `client_reports` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`account` varchar(255) DEFAULT NULL,
`friendly_name` varchar(255) DEFAULT NULL,
`sites_id` int(10) DEFAULT NULL,
`service` varchar(255) DEFAULT NULL,
`date` date DEFAULT NULL,
`campaign` varchar(255) DEFAULT NULL,
`adgroup` varchar(255) DEFAULT NULL,
`keyword` varchar(255) DEFAULT NULL,
`impressions` int(10) DEFAULT NULL,
`clicks` int(10) DEFAULT NULL,
`cost` float DEFAULT NULL,
`max_cpc` float DEFAULT NULL,
`avg_pos` float DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `stats` (`impressions`,`clicks`,`cost`),
KEY `date` (`date`),
KEY `campaign` (`campaign`),
KEY `adgroup` (`adgroup`),
KEY `keyword` (`keyword`),
KEY `service` (`service`),
KEY `sites_id` (`sites_id`),
CONSTRAINT `sites_id` FOREIGN KEY (`sites_id`) REFERENCES `client_sites` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=109167 DEFAULT CHARSET=utf8
Edit Again:
client_reports table data viewable at http://pastebin.com/T532W3Eq
client_leads table data viewable at http://pastebin.com/9cjWEvck
SELECT cr.account, cr.campaign, cr.date, COUNT(cl.id) AS number_of_leads
FROM client_reports cr
LEFT JOIN client_leads cl
ON cl.source = cr.campaign
GROUP BY cl.source