mysql workbench duplicate key error - mysql
I have a data set with a list of country names, and the country names are repeated once for "Males" and then again for "Females".
For example:
c_name gender
China M
Greece M
Algeria M
China F
Greece F
Algeria F
When I create table and import data from a csv file, I get a 'duplicate key' error. I am wondering if this has anything to do with the engine settings? Any ideas how this can be resolved? (I know it works because my friend got it to work on her Mac, and she did not have the option to choose 'Collate' or 'Engine' when creating her tables, but I'm on Windows)
EDIT: Here's how I'm creating the table:
CREATE TABLE dbs.enrollment (
e_id INT NOT NULL,
c_name VARCHAR(45) NOT NULL,
gender VARCHAR(45) NULL,
2001 INT NULL,
2002 INT NULL,
2003 INT NULL,
2004 INT NULL,
2005 INT NULL,
2006 INT NULL,
2007 INT NULL,
2008 INT NULL,
2009 INT NULL,
2010 INT NULL,
PRIMARY KEY (e_id, c_name));
Your friend might set a primary key with c_name in this table ,if you want to have a change ,you can cancel the primary key。
It would be better to answer if you shared the query which is used for the above. I agree with Walker Li.
If your query is something like this..
CREATE TABLE enrollment (
c_name VARCHAR(255) NOT NULL,
gender VARCHAR(255) NOT NULL,
PRIMARY KEY (c_name)
);
You can change it by removing the primary id line as
CREATE TABLE enrollment (
c_name VARCHAR(255) NOT NULL,
gender VARCHAR(255) NOT NULL
);
Hope this solves your problem.
If your csv data contains any unique column as ID you could use it as primary key as,
CREATE TABLE enrollment (
e_id INT NOT NULL,
gender VARCHAR(255) NOT NULL,
PRIMARY KEY (e_id)
);
A table can have only one primary key. Remove c_name in the last line and only have e_id as shown below
PRIMARY KEY (e_id);
The combination of e_id and c_name must be unique. If not you can create an additional artifical primary key as work around.
CREATE TABLE `enrollment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`e_id` int(11) NOT NULL,
`c_name` varchar(45) NOT NULL,
`gender` varchar(45) DEFAULT NULL,
`2001` int(11) DEFAULT NULL,
`2002` int(11) DEFAULT NULL,
`2003` int(11) DEFAULT NULL,
`2004` int(11) DEFAULT NULL,
`2005` int(11) DEFAULT NULL,
`2006` int(11) DEFAULT NULL,
`2007` int(11) DEFAULT NULL,
`2008` int(11) DEFAULT NULL,
`2009` int(11) DEFAULT NULL,
`2010` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Related
Can't solve errno: 150 "Foreign key constraint is incorrectly formed"
I've been trying to fix the error mentioned in the title with no luck. My data types and lengths are the same and I've also set the ENGINE and CHARSET. Please take a look at my code. Users table: CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, sa_id VARCHAR(30) NOT NULL, name VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL, address1 VARCHAR(70), address2 VARCHAR(70) NOT NULL, suburb VARCHAR(50) NOT NULL, city VARCHAR(30) NOT NULL, province VARCHAR(30) NOT NULL, zip INT(6) NOT NULL, email VARCHAR(70) NOT NULL, password CHAR(32) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Votes table: CREATE TABLE votes ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, sa_id VARCHAR(30) NOT NULL, party VARCHAR(30) NOT NULL, province VARCHAR(50) NOT NULL, FOREIGN KEY (sa_id) REFERENCES users(sa_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Error: Can't create table 'savs_db'.'votes' (errno: 150 "Foreign key constraint is incorrectly formed")
Took #Michal Hynčica's advice and found the solution. I failed to index the non-key column I was referencing. I added INDEX (sa_id) to line 14. Solution: CREATE TABLE IF NOT EXISTS users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, sa_id VARCHAR(30) NOT NULL, name VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL, address1 VARCHAR(70), address2 VARCHAR(70) NOT NULL, suburb VARCHAR(50) NOT NULL, city VARCHAR(30) NOT NULL, province VARCHAR(30) NOT NULL, zip INT(6) NOT NULL, email VARCHAR(70) NOT NULL, password CHAR(32) NOT NULL, INDEX (sa_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
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.
SQL JOIN query issue provides inaccurate return
I have spend hours searching for this specific issue on the site though many are close not address it completely. Please link it if it exists and I will happily take down this question. I have two tables wb_states and wb_cities you can see by the keys: composite state_code+country_code & city_id are distinctive for their respective tables. OBJECTIVE: run a JOIN query to pull in the state_name from the wb_states table (in place of the state_code) I always get the sql_mode=only_full_group_by ERROR unless I use the following SELECT ANY_VALUE(c.city_id) as id, ANY_VALUE(c.city_ascii) as ci, ANY_VALUE(s.state_name_ascii) as ps, ANY_VALUE(c.country_code) as co FROM wb_cities AS c JOIN wb_states AS s ON s.state_code=c.state_code WHERE c.city_ascii like 'aa%' GROUP BY id ORDER BY co,ps,ci ASC Of course the query works but the moment we employ ANY_VALUE it fails. Unique id 2959927 - city of Aalen belongs to only one province Baden-Wurttemberg. How do you construct this query? Thank you. CREATE TABLE `wb_cities` ( `city_id` int(11) NOT NULL, `city_name` varchar(65) DEFAULT NULL, `city_ascii` varchar(65) DEFAULT NULL, `state_code` varchar(55) DEFAULT NULL, `state_name_ascii` varchar(45) DEFAULT NULL, `country_code` varchar(45) DEFAULT NULL, `country_full` varchar(55) DEFAULT NULL, `lat` varchar(45) DEFAULT NULL, `lon` varchar(45) DEFAULT NULL, PRIMARY KEY (`city_id`) ) CREATE TABLE `wb_states` ( `id` int(11) DEFAULT NULL, `state_code` varchar(10) NOT NULL, `state_name` varchar(45) DEFAULT NULL, `state_name_ascii` varchar(45) DEFAULT NULL, `country_code` varchar(45) NOT NULL, PRIMARY KEY (`state_code`,`country_code`) ) INSERT INTO `wb_cities` VALUES (14256,'Āzādshahr','Azadshahr','09','Hamadan','IR','Iran','34.79049','48.57011'),(18918,'Protaras','Protaras','01','Famagusta','CY','Cyprus','35.0125','34.05833'),(23814,'Kahrīz','Kahriz','13','Kermanshah','IR','Iran','34.3838','47.0553'),(24851,'Nūrābād','Nurabad','23','Lorestan','IR','Iran','34.0734','47.9725'),(32723,'Īstgāh-e Rāh Āhan-e Garmsār','Istgah-e Rah Ahan-e Garmsar','25','Semnan','IR','Iran','35.23455','52.30942'),(32767,'Qarchak','Qarchak','26','Tehran','IR','Iran','35.42867','51.57544'),(32909,'Shahre Jadide Andisheh','Shahre Jadide Andisheh','26','Tehran','IR','Iran','35.6803','51.0193'),(41210,'Khorramdarreh','Khorramdarreh','36','Zanjan Province','IR','Iran','36.20898','49.19152'),(50672,'Wanlaweyn','Wanlaweyn','14','Shabeellaha Hoose','SO','Somalia','2.6185','44.8938'),(52867,'Qoryooley','Qoryooley','14','Shabeellaha Hoose','SO','Somalia','1.78784','44.52999'); INSERT INTO `wb_states` VALUES (29,'00','Armenia','Armenia','AM'),(11,'00','Aruba','Aruba','AW'),(15,'00','Bosnia and Herzegovina','Bosnia and Herzegovina','BA'),(31,'00','Botswana','Botswana','BW'),(7,'00','Belarus','Belarus','BY'),(23,'00','Cook Islands','Cook Islands','CK'),(39,'00','Christmas Island','Christmas Island','CX'),(4,'00','Czech Republic','Czech Republic','CZ'),(17,'00','Western Sahara','Western Sahara','EH'),(10,'00','Falkland Islands (Islas Malvinas)','Falkland Islands (Islas Malvinas)','FK'),(26,'00','Abkhazia','Abkhazia','GE'),(27,'00','Ghana','Ghana','GH'),(37,'00','Gibraltar','Gibraltar','GI'),(3,'00','Equatorial Guinea','Equatorial Guinea','GQ'),(16,'00','South Georgia and The South Sandwich Islands','South Georgia and The South Sandwich Islands','GS'),(28,'00','Hong Kong','Hong Kong','HK'),(6,'00','Indonesia','Indonesia','ID'),(8,'00','Ireland','Ireland','IE'),(32,'00','Kyrgyzstan','Kyrgyzstan','KG'),(36,'00','Comoros','Comoros','KM'),(34,'00','Muḩāfaz̧atalWafrah','MuhafazatalWafrah','KW'),(19,'00','Zhezqazghan Oblysy','Zhezqazghan Oblysy','KZ'),(21,'00','Lithuania','Lithuania','LT'),(40,'00','Monaco','Monaco','MC'),(13,'00','Montenegro','Montenegro','ME'),(9,'00','Mali','Mali','ML'),(5,'00','Macedonia','Macedonia','MO'),(35,'00','Mauritius','Mauritius','MU'),(25,'00','Malaysia','Malaysia','MY'),(41,'00','Norfolk Island','Norfolk Island','NF'),(30,'00','Bāgmatī Zone','Bagmati Zone','NP'),(2,'00','Niue','Niue','NU'),(14,'00','Panama','Panama','PA'),(22,'00','Philippines','Philippines','PH'),(42,'00','Palestine','Palestine','PS'),(43,'00','Serbia','Serbia','RS'),(24,'00','Swaziland','Swaziland','SZ'),(20,'00','Turks and Caicos Islands','Turks and Caicos Islands','TC'),(33,'00','Turkmenistan','Turkmenistan','TM'),(38,'00','Turkey','Turkey','TR'),(12,'00','British Virgin Islands','British Virgin Islands','VG'),(18,'00','Zimbabwe','Zimbabwe','ZW'),(164,'01','Abū Z̧aby','Abu Zaby','AE'),(90,'01','Badakhshan','Badakhshan','AF'),(112,'01','Barbuda','Barbuda','AG'),(118,'01','Aragatsotn','Aragatsotn','AM'),(124,'01','Benguela','Benguela','AO'),(45,'01','Buenos Aires','Buenos Aires','AR'),(146,'01','Burgenland','Burgenland','AT');
You join wb_cities to wb_states only on state_code but you should also use country_code, because state_code is not unique in wb_states. Also I don't see any reason for aggregation. You need only a join of the tables: SELECT c.city_id id, c.city_ascii ci, s.state_name_ascii ps, c.country_code co FROM wb_cities AS c JOIN wb_states AS s ON s.state_code=c.state_code AND s.country_code = c.country_code WHERE c.city_ascii like 'aa%' ORDER BY co, ps, ci
Your data model is broken. Here are two definitions of state_code: `state_code` varchar(55) `state_code` varchar(10) And yet this is part of an undeclared foreign key relationship. I think this is the root problem: PRIMARY KEY (`state_code`, `country_code`) Presumably, the ID is unique, so you should have: CREATE TABLE `wb_states` ( `state_id` int(11) DEFAULT PRIMARY KEY, `state_code` varchar(10) NOT NULL, `state_name` varchar(45) DEFAULT NULL, `state_name_ascii` varchar(45) DEFAULT NULL, `country_code` varchar(45) NOT NULL, `country_full` varchar(55) DEFAULT NULL, UNIQUE (`state_code`,`country_code`) ); Then, your wb_cities table can be appropriately defined as: CREATE TABLE `wb_cities` ( `city_id` int(11) NOT NULL PRIMARY KEY, `city_name` varchar(65) DEFAULT NULL, `city_ascii` varchar(65) DEFAULT NULL, `state_id` int DEFAULT NULL, `lat` varchar(45) DEFAULT NULL, `lon` varchar(45) DEFAULT NULL, PRIMARY KEY (`city_id`), FOREIGN KEY (state_id) REFERENCES wb_states(state_id) ); You should probably have a "countries" table as well, but at least the country can go in the "states" table rather than the "cities" table. Then, the "state" information can be looked up using the state_id. After you have fixed the data model, you can think about fixing the query.
Foreign Keys in MySQL Workbench not working?
I am reverse engineering a database in MySQL Workbench but it doesn't seem to be importing or recognising the foreign keys. Which means I cant get it to draw the relationships. While I am trying to get this to work I am using a snippet of a couple of tables, so its nothing complex. Here are the 2 demo tables that I am trying to get to work: CREATE TABLE users ( UserID varchar(32) NOT NULL, OrgID varchar(6) NOT NULL, RegionID int NULL, LocationID int NULL, Name nvarchar(60) NULL, Crypt varchar(32) NULL, Security int NULL, Status int NULL, PRIMARY KEY ( UserID ), CONSTRAINT fk_OrgID_Users FOREIGN KEY (OrgID) REFERENCES Organisations(OrgID) ); CREATE TABLE Organisations( OrgID varchar(6) NOT NULL, Name nvarchar(70) NOT NULL, Address1 varchar(50) NULL, Address2 varchar(50) NULL, Address3 varchar(50) NULL, Town varchar(20) NULL, County varchar(20) NULL, PostCode varchar(10) NULL, NotificationEmail varchar(500) NOT NULL, PRIMARY KEY ( OrgID ) ) But in MySQL Workbench, there are no relationships or foreign keys being created. If I look at the table data, and the foreign keys tab, theres nothing there? I think I'm creating the foreign keys correctly, so is there a reason its not importing them?
On further research there were several things that I needed to do for this to work. I had to make sure that the tables reverse engineered from MySQL were defined as InnoDB. And I also had to remove the foreign key constraint from the create table command and create the foreign keys after the tables were created, like so: CREATE TABLE Users ( UserID varchar(32) NOT NULL, OrgID varchar(6) NOT NULL, RegionID int NULL, LocationID int NULL, Name nvarchar(60) NULL, Crypt varchar(32) NULL, Security int NULL, Status int NULL, PRIMARY KEY ( UserID ) ) ENGINE=InnoDB; CREATE TABLE Organisations( OrgID varchar(6) NOT NULL, Name nvarchar(70) NOT NULL, Address1 varchar(50) NULL, Address2 varchar(50) NULL, Address3 varchar(50) NULL, Town varchar(20) NULL, County varchar(20) NULL, PostCode varchar(10) NULL, NotificationEmail varchar(500) NOT NULL, PRIMARY KEY ( OrgID ) ) ENGINE=InnoDB; ALTER TABLE Users ADD CONSTRAINT fk_OrgID_Users FOREIGN KEY (OrgID) REFERENCES Organisations(OrgID); This then worked fine and the relationships were visible and connected in MySQL Workbench
Using composite key as a foreign key in mysql
My Tables Fee Table CREATE TABLE IF NOT EXISTS `fee` ( `feeNumber` int(11) NOT NULL, `feeName` varchar(255) NOT NULL, `feeDescription` varchar(255) DEFAULT NULL, `feeAmount` varchar(255) NOT NULL, `universityName` varchar(255) NOT NULL ) ADD PRIMARY KEY (`feeNumber`,`feeName`,`feeAmount`) Housing Table CREATE TABLE IF NOT EXISTS `housing` ( `housingOfficeNumber` int(11) NOT NULL, `housingOfficeName` varchar(50) NOT NULL DEFAULT '', `housingOfficeType` varchar(50) DEFAULT NULL, `housingOfficePhone` decimal(18,0) DEFAULT NULL, `housingOfficeRoomDeposit` varchar(50) DEFAULT NULL, `studentStatusName` varchar(50) DEFAULT NULL, `housingFeeNumber` int(11) NOT NULL, `housingFeeName` varchar(255) NOT NULL, `housingFee` int(255) DEFAULT NULL, `hOffTrm` varchar(50) DEFAULT NULL, `universityName` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; What I'm trying to do is reference the feeAmount,feeNumber, and feeName from the fee table and add it to the housingfee, housingfeeName, and housingFeenumber columns in the housing table. Since the feeAmount and feeName columns are not unique I decided to make a composite key out of feeNumber, feeName, and feeAmount. The only part of the composite key I really need referenced is feeAmount. feeName and feeNumber are not really important. using phpmyadmin.
No, no, no. In general, I think it is best to avoid compound primary keys. In this case, in particular, you do not want the fee amount or name to be part of the key. In order to access the row, you need to know the amount. That seems very difficult to implement. I am guessing that an auto incremented primary key will work just fine. You can then add a separate unique constraint on other columns. So: CREATE TABLE IF NOT EXISTS `fee` ( `feeNumber` int(11) NOT NULL auto_increment primary key, `feeName` varchar(255) NOT NULL, `feeDescription` varchar(255) DEFAULT NULL, `feeAmount` varchar(255) NOT NULL, `universityName` varchar(255) NOT NULL, unique (feeName) ); Then, another table would have feeNumber with an appropriate foreign key reference. Through the reference, you can get other information -- such as the name and amount -- using a join.