Mysql how to add more than one value (in one box) - mysql

I am trying to add more than one value
INSERT INTO Requierments (item_ID, SName) VALUES (
05, 'Exotic Weapons''basic weapon');
is that possible? i have all ready tried | and & but i am not allowed to do that.
the idea is to demonstrate that item_ID requires more than one Sname.
and if no SName are needed, how do i code that, in the alter table it shows me that they are by default '0' for item_ID and '' for Sname, but when i try:
INSERT INTO Requierments (item_ID, SName) VALUES (
02, '');
or
INSERT INTO Requierments (item_ID, SName) VALUES (
02, );
error occurs. item_ID and SName are the primary key and foreign key to two different tables
CREATE TABLE `requierments` (
`item_ID` int(11) NOT NULL DEFAULT '0',
`SName` varchar(30) NOT NULL DEFAULT '',
PRIMARY KEY (`item_ID`,`SName`),
KEY `SName` (`SName`),
CONSTRAINT `requierments_ibfk_1` FOREIGN KEY (`item_ID`) REFERENCES `item` (`ID`),
CONSTRAINT `requierments_ibfk_2` FOREIGN KEY (`SName`) REFERENCES `talents` (`SkillName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `talents` (
`SkillName` varchar(40) NOT NULL DEFAULT '',
`Bonus` varchar(30) DEFAULT NULL,
`Description` varchar(90) DEFAULT NULL,
`R_Str` int(11) DEFAULT NULL,
`R_WS` int(11) DEFAULT NULL,
`R_BS` int(11) DEFAULT NULL,
`R_Fel` int(11) DEFAULT NULL,
`R_Per` int(11) DEFAULT NULL,
`R_Int` int(11) DEFAULT NULL,
`R_Agi` int(11) DEFAULT NULL,
`R_WP` int(11) DEFAULT NULL,
`Talent_requiret` varchar(40) DEFAULT NULL,
PRIMARY KEY (`SkillName`),
KEY `Talent_requiret` (`Talent_requiret`),
CONSTRAINT `talents_ibfk_1` FOREIGN KEY (`Talent_requiret`) REFERENCES `talents` (`SkillName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `item` (
`ID` int(11) NOT NULL DEFAULT '0',
`Name_` varchar(30) DEFAULT NULL,
`Weight` int(11) DEFAULT NULL,
`Value_` int(11) DEFAULT NULL,
`Availability` varchar(30) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here are the 3 tables where i want to store in the requirement table what item_ID requires to be used under SName, since one item can be required to have more than one SName or none, it get confused on what to do.

The 'Exotic Weapons''basic weapon' syntax is interpreted as 'Exotic Weapons'basic weapon' (see the manual page on String Literals). You can store both, if you separate them with a special character like a comma or something ('Exotic Weapons,basic weapon'), but this is a bad idea, for the reasons that follow.
Anytime you are tempted to store multiple values in one column, you should have a new table to store each value and link it to the item_ID in question. This is called "normalization" - it makes your database more stable, your application code simpler, and everything just more likely to work as you move forward and modify things. Search for "database normalization" and read about how to do the kind of thing you are trying to do.
EDIT: It's still a little hard to tell what you're trying to do, but it looks like you just want to store multiple tuples in items. Example:
INSERT INTO Requierments (item_ID, SName) VALUES
(5, 'Exotic Weapons'),
(5, 'basic weapon');
Note that it should be 5, not 05. That's why INSERT INTO Requierments (item_ID, SName) VALUES ( 02, ''); fails. Also, you can't just omit a value and have blank space, like in your other example: INSERT INTO Requierments (item_ID, SName) VALUES ( 02, );
Honestly, it's very hard to tell what you're even trying to do here, and there seems to be some confusion about the basics of table structure and SQL syntax. For example, this statement is very confusing and unclear: "since one item can be required to have more than one SName or none, it get confused on what to do." If you can provide some more clarity about how you want the tables to relate to each other and where you are stuck, you will get more help from the SO community.

Related

Can you insert ignore into table if certain fields are duplicate?

I am trying to insert into a MySQL table, but I came across a problem that I can't seem to solve. The problem is that I want to add a record into the table if certain fields are duplicate, but not all.
To make my problem more clear this is the table:
When I want to do an insert into this table, I want to insert ignore only if userid and status and url are duplicate. If one of those 3 are unique the record can be added into the table.
What I have tried:
INSERT IGNORE INTO mydb.mytable (unique_screen_id, userid, url, status)
VALUES ('1234', 1, 'something.com', 'active');
This does not give the desired result since unique_screen_id will never be duplicate and thus the statement will insert the record. I can't remove the unique_screen_id out of the query since it also needs to be added into the table
Which query can I use so that if I insert the record above, it will check if userid and status and url are duplicate, and if they are ignore the statement (and otherwise insert the statement)?
Edit:
As requested my create table query:
CREATE TABLE `screens` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I am not sure what your create table statement is like but you can add UNIQUE key:
UNIQUE (userid ,url, status)
Here is a demo
So first you create table like this(without UNIQUE KEY):
CREATE TABLE `screens2` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
then if you add this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 1, '1', 'something.com', 'active');
and then this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 1, '1', 'something.com', 'finished');
and then this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 2, '1', 'something.com', 'finished');
all 3 lines will be inserted...
If you create your table like this:
CREATE TABLE `screens` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
unique(userid, url, status)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Only two of the lines will be inserted and one will be ignored.
P.S. If you add UNIQUE key you will no IGNORE keyword with your insert statements.
As the user VBoka suggested the following demo displays the answer!
I needed to use a combination of the insert ignore statement and the Unique keyword!
Thanks!
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5d19c458568ef9204c257b7ef6096eab

Foreign key constraint fails but referenced row exists

I'm running MySQL 5.7.21 on Amazon RDS.
I know this question has been asked a thousand times, but I'm getting the issue on a scenario I wouldn't expect, so please read through before downvoting or marking as duplicate.
I'm not restoring the database, just running single INSERT queries, so is not a matter of ordering.
The referenced row does exist on the table; me and my colleagues had it triple checked.
As one might expect, disabling the FK checks with SET foreign_key_checks = 0 does make the query work.
I've seen this happening because of different table charsets, but in this case, both use utf8mb4. Also both have collation set to utf8mb4_general_ci.
This is happening in a production environment, so dropping the tables and recreating them is something I would like to avoid.
Some additional information:
The FK constraint was created AFTER the original tables were already populated.
Here is the relevant portion of the current DDL:
CREATE TABLE `VehicleTickets` (
`id` varchar(50) NOT NULL,
`vehiclePlate` char(7) NOT NULL,
`organizationId` varchar(50) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'OPEN',
`description` text NULL DEFAULT NULL,
`ticketInfo` json DEFAULT NULL,
`externalId` varchar(100) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.externalId'))) VIRTUAL,
`value` decimal(10,2) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.value'))) VIRTUAL,
`issuedAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.issuedAt'))) VIRTUAL NOT NULL,
`expiresAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.expiresAt'))) VIRTUAL NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `VehicleTickets_externalId_unq_idx` (`externalId`,`organizationId`),
KEY `VehicleTickets_vehiclePlate_idx` (`vehiclePlate`),
KEY `VehicleTickets_organizationId_idx` (`organizationId`),
KEY `VehicleTickets_issuedAt_idx` (`createdAt`),
KEY `VehicleTickets_expiresAt_idx` (`expiresAt`),
CONSTRAINT `VehicleTickets_Organizations_fk`
FOREIGN KEY (`organizationId`) REFERENCES `Organizations` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `Organizations` (
`id` varchar(50) NOT NULL,
`name` varchar(100) NOT NULL,
`taxPayerId` varchar(50) DEFAULT NULL,
`businessName` varchar(100) DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'TESTING',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`activatedAt` timestamp NULL DEFAULT NULL,
`assetConfiguration` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
When I run:
select * from VehicleTickets where organizationId not in (
select id from Organizations
);
I get an empty result set.
However, if I run a query like this:
insert into `VehicleTickets` (
`id`,
`createdAt`,
`organizationId`,
`ticketInfo`,
`vehiclePlate`
)
values (
'... application generated id',
'... current date ',
'cjlchoksi01r8nfks3f51kht8', -- DOES EXIST on Organizations
'{ ... some JSON payload }',
'... vehicle plate'
)
This produces the following error:
Cannot add or update a child row: a foreign key constraint fails
(VehicleTickets, CONSTRAINT VehicleTickets_Organizations_fk
FOREIGN KEY (organizationId) REFERENCES Organizations (id))
Additionally, it gives me:
"errno": 1452,
"sqlState": "23000",
I've read through several threads regarding this issue, but couldn't find a similar case.

Can I add a Unique key on table creation in SQL?

I am trying to translate a collection of MySQL functions to SQL, and I'm having issues with a UNIQUE KEY issue:
-- -----------------------------------------------------
-- Table testform
-- -----------------------------------------------------
CREATE TABLE `testform` (
`FormId` INT(11) NOT NULL AUTO_INCREMENT,
`TTId` INT(11) NULL DEFAULT NULL,
`TestName` VARCHAR(100) NULL,
PRIMARY KEY (`FormId`),
UNIQUE KEY `TF_Composite` (`TTId`, `TestName`));
When I try and test this in SQLFiddle, it's giving me the error
Incorrect syntax near the keyword 'KEY'.
I have tried searching for this, but so far all I have come up with is "Unique Constraints". Is there a difference between a "Key" and a "Constraint" in SQL? And if so, how can I add this in the table creation statement?
Your syntax is all messed up. Please look at books on-line (MSDN).
https://msdn.microsoft.com/en-us/library/ms174979.aspx
The sample code below create a table in tempdb. This table automatically gets destroyed when the service is restarted.
-- Just a example, throw away after reboot
USE [tempdb]
GO
-- Create the table
CREATE TABLE DBO.TESTFORM
(
FORM_ID INT IDENTITY(1, 1) NOT NULL ,
TT_ID INT NULL,
TEST_NAME VARCHAR(100) NULL,
CONSTRAINT PK_FORM_ID PRIMARY KEY (FORM_ID),
CONSTRAINT UN_COMPOSIT UNIQUE (TT_ID, TEST_NAME)
);
-- Seventies Band
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (1, 'John');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (2, 'Paul');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (3, 'Mary');
GO
-- Show data
SELECT * FROM TEMPDB.DBO.TESTFORM
GO
The image below shows the data in this table.
Try This.
CREATE TABLE testform (
FormId INT(11) NOT NULL AUTO_INCREMENT,
TTId INT(11) NULL DEFAULT NULL,
TestName VARCHAR(100) NULL,
PRIMARY KEY (FormId),
CONSTRAINT TF_Composite UNIQUE (TTId,TestName));
More Details..
For Better Understanding about Primary and Unique you can refer below page.
Primary and Unique Key Creation
For MySQL Database
CREATE TABLE `phone` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`country` DECIMAL(5,0) UNSIGNED NOT NULL,
`area` DECIMAL(5,0) UNSIGNED NOT NULL,
`number` DECIMAL(8,0) UNSIGNED NOT NULL,
`extension` DECIMAL(5,0) UNSIGNED DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ix_phone` (`country`, `area`, `number`, `extension`),
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
For alter Table :
ALTER TABLEphone
ADD UNIQUE INDEXix_phone(country,area,number,extension);

Adding Foreign Key Error

I want to add a foreign key from Table Customers, row= "Customer ID" to Table Pet, row= "Customer ID".
-- Table structure for table `Customers`
CREATE TABLE IF NOT EXISTS `Customers` (
`CustomerID` varchar(50) NOT NULL,
`Fname` varchar(50) DEFAULT NULL,
`LName` varchar(20) DEFAULT NULL,
`Tel` varchar(20) DEFAULT NULL,
`Fax` varchar(20) DEFAULT NULL,
`CustType` varchar(20) DEFAULT NULL,
`AdState` varchar(50) DEFAULT NULL,
`City` varchar(20) DEFAULT NULL,
`Zip` varchar(20) DEFAULT NULL,
`Street` varchar(20) DEFAULT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `Customers`
INSERT INTO `Customers` (`CustomerID`, `Fname`, `LName`, `Tel`, `Fax`, `CustType`, `AdState`, `City`, `Zip`, `Street`) VALUES
('AC001', 'All', 'Creatures', '206 555-6622', '206 555-7854', '2', 'WA', 'Tall Pines', '98746', '21 Grace St.'),
('AD001', 'Johnathan', 'Adams', '206 555 7623', '206 555 8855', '1', 'WA', 'Mountain View', '984101012', '66 10th St'),
('AD002', 'William', 'Adams', '503 555 7623', '503 555 7319', '1', 'OR', 'Lakewille', '9740110011', '1122 10th_St'),
('AK001', 'Animal', 'Kingdom', '208 555 7108', '', '2', 'ID', 'Borderville', '834835646', '15 Marlin Lane');
CREATE TABLE IF NOT EXISTS `Pet` (
`ID` varchar(50) NOT NULL,
`CustomerID` varchar(50) NOT NULL,
`Gender` varchar(20) DEFAULT NULL,
`Race` varchar(20) DEFAULT NULL,
`Name` varchar(20) DEFAULT NULL,
`Kind` varchar(20) DEFAULT NULL,
`Birthday` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Dumping data for table `Pet`
INSERT INTO `Pet` (`ID`, `CustomerID`, `Gender`, `Race`, `Name`, `Kind`, `Birthday`) VALUES
('AC001-01', '0', 'M', 'Long Ear', 'Bobo', 'Rabbit', '4/8/92'),
('AC001-02', '0', 'F', 'Chameleon', 'Presto Chango', 'Lizard', '5/1/92'),
('AC001-03', '0', 'M', '', 'Stinky', 'Skunk', '8/1/91'),
('AC001-04', '0', 'M', 'German Shepherd', 'Fido', 'Dog', '6/1/90'),
('AD001-01', '0', 'F', 'Potbelly', 'Patty', 'Pig', '2/15/91'),
('AD001-02', '0', 'M', 'Palomino', 'Rising Sun', 'Horse', '4/10/90'),
('AD002-01', '0', 'F', 'Mixed', 'Dee Dee', 'Dog', '2/15/91'),
('AK001-03', '0', 'M', '', 'Jerry', 'Rat', '2/1/88'),
('AK001-07', '0', 'M', 'Beagle', 'Luigi', 'Dog', '8/1/92');
This is the code that I have been using to add the foreign key:
ALTER TABLE Pet ADD CONSTRAINT Pet_FK
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID);
And the error message from this is:
#1452 - Cannot add or update a child row: a foreign key constraint fails
(`hospital`.`#sql-523_76e`, CONSTRAINT `Pet_FK` FOREIGN KEY (`CustomerID`)
REFERENCES `Customers` (`CustomerID`))
I am quite a beginner with database and I have no idea what I should try next.
I think that's all. Im still new to this stackoverflow so if I missed any necessary information please tell me and I will add it.
UPDATE***
ALTER TABLE Customers ADD CONSTRAINT Customers_FK
FOREIGN KEY (CustomerID) REFERENCES Pet (CustomerID);
I swapped some positions and the error code I recieve is:
#1215 - Cannot add foreign key constraint
Simple one.
There is an row that contains the CustomerID that can't be matched. So first you need to remove/edit/handle the entry and than add a foreign key.
The CustomerID you're trying to enter in PETS table, does not exist in CUSTOMERS table, and that is why your Foreign Key constraint fails and throws error.
You need to ensure that the CustomerIDs you're entering in your Pets table, exist in Customers table OR simply insert NULL in the PETS.CUSTOMERID field
Enterx is right.
For being able to detect not matching row :
SELECT * FROM Pet p WHERE (SELECT COUNT(*) FROM Customers c WHERE c.CustomerID=p.CustomerID)=0
Just change SELECT * by DELETE for deleting missmatching Pet entry.
You can UPDATE Pet.CustomerID to NULL too. But you have to define CustomerID, from Pet table, with NULL option (and not NOT NULL)
It looks like to me that you inserted values in table Pet's column ID when they should have been inserted in CustomerID and vice-versa.
By the way, it's not really good to have IDs as VARCHARs, specially when they are foreign keys. This makes queries processing slower, although your tables don't look like they'll have a huge number of rows for this to make a difference. Anyway, it's just an observation. I would consider have artificial int primary keys in my tables.
EDIT
I had misread table Pet's values. The other answers here are right. You need to update those 0 values in CustomerID column to match existing CustomerIDs in Customer table or delete them, otherwise you'll get an error when trying to create the FK.
try this
CREATE TABLE IF NOT EXISTS `Pet` (
`ID` varchar(50) NOT NULL,
FOREIGN KEY (`CustomerID`) REFERENCES Customers(CustomerID) varchar(50) NOT NULL,
`Gender` varchar(20) DEFAULT NULL,
`Race` varchar(20) DEFAULT NULL,
`Name` varchar(20) DEFAULT NULL,
`Kind` varchar(20) DEFAULT NULL,
`Birthday` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

mysql error 1451

I have mysql error with code 1451.
Cannot delete or update a parent row: a foreign key constraint fails (online_store_admin.osa_admin_logs, CONSTRAINT fk_admins_logs FOREIGN KEY (aid) REFERENCES osa_admins (aid))
here sql statement :
drop table if exists osa_admins;
create table if not exists osa_admins(
aid int unsigned not null auto_increment,
uid varchar(50) not null,
pass char(41) not null,
erp_id int unsigned not null,
last_login int unsigned not null,
is_block tinyint unsigned not null,
menus varchar(50) not null,
is_login tinyint unsigned not null,
ip_login char(15) not null,
constraint idx_osa_admins primary key using btree(aid)
);
insert into osa_admins value
(NULL, 'root', password('6789'), '0', '0', '0', '*', '0', '127.000.000.001'),
(NULL, 'ryu', password('6789'), '0', '0', '0', '*', '0', '127.000.000.001');
drop table if exists osa_admin_logs;
create table if not exists osa_admin_logs(
lid bigint unsigned not null,
aid int unsigned not null,
dates int unsigned not null,
logs text not null,
constraint idx_osa_admin_logs primary key using btree(lid),
constraint fk_admins_logs foreign key (aid)
references osa_admins(aid)
match full
on update cascade
on delete cascade
);
insert into osa_admin_logs values
(NULL, '2', '0', 'some action here'),
(NULL, '2', '0', 'again, some action here');
Problem come when i use this statement:
delete from osa_admins where aid='2';
i think i had set "on delete cascade". anyone know how to delete cascade? so i don't necessary to manual detelet osa_admin_logs data. oh, i using innodb as db engine(default mysql that i have).
And sorry i ask same question that had answer, just let me know where i can get my question.
Thank You.
Use the following commands to do this:
SET foreign_key_checks = 0;
DELETE FROM your_table_name WHERE your_condition;
SET foreign_key_checks = 1;
remove the match full from the constraint
Use of an explicit MATCH clause will
not have the specified effect, and
also causes ON DELETE and ON UPDATE
clauses to be ignored. For these
reasons, specifying MATCH should be
avoided.
MySql docs https://dev.mysql.com/doc/refman/8.0/en/create-table.html