I'm using MYSQL script and I want to insert some values in a table.
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
But I only want to insert if the table is empty in the first place.
I'm not a SQL guy but basically
if(testType.length() == 0 {
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
}
How can I do this the simplest and smallest way possible? Thank you.
EDIT: my question is different. I want to insert ALL THE DATA if the table is empty. not only one insert at the time
First, I would suggest doing this in one step:
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL');
Then, you can express this without IF:
INSERT INTO testType(name)
SELECT t.name
FROM (SELECT 'URL' as name UNION ALL
SELECT 'xD' as name UNION ALL
SELECT 'LOL' as name
) t
WHERE NOT EXISTS (SELECT 1 FROM testType);
Finally, if you want to insert these values if each doesn't exist, then you can let the database do the work. First, define a unique constraint/index on the name (if name is not already the primary key), and then use ON DUPLICATE KEY UPDATE:
CREATE UNIQUE INDEX unq_testtable_name ON testtable(name);
INSERT INTO testType(name)
VALUES ('URL'), ('xD'), ('LOL')
ON DUPLICATE KEY UPDATE name = VALUES(name);
You can use stored procedure
DELIMITER //
CREATE PROCEDURE `proc1` ()
BEGIN
SELECT COUNT(*) INTO variable1 FROM testType;
IF variable1 = 0 THEN
INSERT INTO `testType` (`name`) VALUES ('URL');
INSERT INTO `testType` (`name`) VALUES ('xD');
INSERT INTO `testType` (`name`) VALUES ('LOL');
END WHILE;
END //
Try this:
DECLARE #ExistCount INT;
SET #ExistCount = (SELECT COUNT(1) FROM `testType`);
IF #ExistCount<1
THEN
INSERT INTO `testType` (`name`) VALUES ('URL'),('xD'),('LOL');
END IF;
Related
Insert Into table if a duplicate exits select that row primary key else insert into that table and return last insert id ?
SELECT IF (EXISTS(SELECT * FROM users WHERE userName='adminchat')) THEN
BEGIN
SELECT userId FROM users WHERE userName='adminchat';
end;
ELSE
BEGIN
INSERT INTO `users`( `userRole`, `userName`, `createdOn`, `emailId`, `is_active`, `password`) VALUES (1,'user1_chat',NOW(),'sdmd1#sdmd1.com',1,'123456')
select LAST_INSERT_ID();
END;
If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
A way to make things work is to use a dummy column,
so if you have a table with auto_increment column ID and unique key a,b and a smallint dummy column for instance, the query might look like this:
INSERT INTO test (a,b) VALUES ('1','2') ON DUPLICATE KEY UPDATE ID=LAST_INSERT_ID(ID),Dummy = NOT dummy;
Now, SELECT LAST_INSERT_ID(); will return the correct ID.
I've got an INSERT ... ON DUPLICATE KEY UPDATE query and I am trying to add WHERE clause to it:
INSERT INTO `product_description` (
`product_id`,`language_id`,`name`,
`description`,`meta_description`,
`meta_keyword`,`tag`
) VALUES (
$getProductId, $languageId, '$pName', '$pDescription', '', '', ''
)
ON DUPLICATE KEY UPDATE
`name` = '$pName',
`description` = '$pDescription'
I want to restrict the UPDATE to those 2 conditions:
WHERE `model` = 'specific-model' AND `sku` NOT LIKE '%B15%'
If I add this part of query to the end of the original query I get a MySQL syntax error. What would be a working solution?
Update: Please note that model and sku are in another table, and the common key is product_id
I would suggest you to use some sort of prepared statement instead of concatenating strings, so you should do something like this:
INSERT INTO `product_description` (
`product_id`, `language_id`, `name`,
`description`, `meta_description`,
`meta_keyword`, `tag`
) VALUES (?, ?, ?, ?,'','','')
but this is not part of the question.
I was thinking of answering with a simple CASE WHEN but the challenging part of your question is that the restrict conditions are not in the product_description table but are from another table. So I think we can just use a TRIGGER:
CREATE TRIGGER product_description_upd
BEFORE UPDATE ON product_description
FOR EACH ROW
IF NOT EXISTS(SELECT * FROM models
WHERE product_id=new.product_id
AND model='Abc' AND `sku` NOT LIKE '%B15%') THEN
SET new.name=old.name;
SET new.description=old.description;
END IF;
//
then you can use an INSERT query like:
INSERT INTO `product_description` (col1, col2, ...)
VALUES (..., ..., ...)
ON DUPLICATE KEY
UPDATE name=VALUE(name),description=VALUE(description)
Please see a fiddle here.
The only thing to note here is that even a standard UPDATE query will be affected.
CREATE TABLE product_description (
product_id INT PRIMARY KEY,
name VARCHAR(100),
description VARCHAR(100)
);
CREATE TABLE models (
product_id INT,
model VARCHAR(100),
sku VARCHAR(100)
);
INSERT INTO models VALUES
(1, "Abc", "ZZZ"),
(2, "Abc", "B15");
INSERT INTO product_description VALUES
(1, "Car", "Red"),
(2, "Truck", "Pink");
INSERT INTO `product_description` VALUES (1, "NewCar", "DeepRed")
ON DUPLICATE KEY UPDATE name=VALUES(name), description=VALUES(description);
Assuming, product_id must be in models.
INSERT INTO `product_description` (product_id, name, description)
SELECT models.product_id, "SuperCar" as name, "DarkRed" as description
FROM `models` WHERE model="Abc" AND `sku` NOT LIKE "%B15%"
ON DUPLICATE KEY UPDATE name="UpdatedCar", description="UpdatedRed";
refer to http://sqlfiddle.com/#!9/69624e/1
Hopefully this solves the problem. You can play with SELECT query for different result.
I have created two tables which i want to insert similar data in.
CREATE TABLE one(
one_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (one_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE two(
two_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (two_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
every time in run insert.
To do that,i am using transactions
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
This does not produce new values on new inserts.It however inserts the same data in the field name as i wanted.
How can i make this work?.
I don't see a need to move to transactions in order to do that, just add an before insert trigger to the table .
Something like :
CREATE TRIGGER `ONE_TABLE_TRIGG` BEFORE INSERT ON `one`
FOR EACH
ROW BEGIN
SET NEW.name= UUID( );
END ;
You can check if it's null before doing that. do this on both tables and you're good or add insert to the other table on 1 trigger.
I solved it without much complexities by having several having several transaction statements in the same file
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
START TRANSACTION;
SET #name = uuid();
INSERT INTO one(one_id,name) VALUES (Null,#name);
INSERT INTO two(two_id, name) VALUES (Null, #name);
COMMIT;
/*
Etc
*/
I have table with several cols and I'm doing a multiplier insert to it.
ie:
INSERT INTO accounting_positions
KEYS (`date`, `customer`, `type`, `product`, `volume`, `payout`, `count`)
VALUES ('2012-01-10','10','regular','60sec',65,83,13),
('2012-01-10','10','regular','binary',15,83,13)
ON DUPLICATE KEY UPDATE volume=volume+CURRENT_COL_VAL;
what should I write instead of the "CURRENT_COL_VAL"?
if I want to update the duplicate row with a value from my insert.
because I cant place a static number inside it because it is differs with every row insert in the multiple insert
have a look at the mysql docu on insert-on-duplicate From there you can see that you can use something like this:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
in your case:
INSERT INTO accounting_positions
(`date`, `customer`, `type`, `product`, `volume`, `payout`, `count`)
VALUES
('2012-01-10','10','regular','60sec',65,83,13),
('2012-01-10','10','regular','binary',15,83,13)
ON DUPLICATE KEY UPDATE volume=volume+VALUES(volume);
which would add the new and the old value. If you only want the given insert value to overwirite the row then do: ON DUPLICATE KEY UPDATE volume=VALUES(volume)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (ID=4,Name='xxx')
or
INSERT INTO MyTable (Name) VALUES (Name='xxx')
The problem is that both INSERT statements produce the entry (4,0). Why 0 instead of "xxx"?
UPDATE: Primary key changed.
This should do the job :
INSERT INTO MyTable (ID, Name) VALUES (4, 'xxx')
I'm pretty sure it would be something like this, instead...
INSERT INTO MyTable (Name) VALUES ('xxx')
No need for the Name= part, since you've already specified which column you wish to insert into with the first (Name) definition.
Because the expression Name='xxx' is false, hence evaluates as zero.
You use the column=expression method use in on duplicate key update clauses as described here, not in the "regular" section of inserts. An example of that:
insert into mytable (col1,col2) values (1,2)
on duplicate key update col1 = col1 + 1
You should be using the syntax:
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
Is that syntax of Name='xxx' valid? Never seen it before, i assume it is seeing it as an unquoted literal, trying to convert it to a number and coming up with 0? I'm not sure at all
Try this:
INSERT INTO MyTable (Name) VALUES ('xxx')
This is because you should mention the name of the column in the values part. And also because you do not define you primary key correctly (airlineID is not part of the field list)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
INSERT INTO MyTable (Name) VALUES ('xxx')
Try this
INSERT INTO MyTable (ID,Name) VALUES (4,xxx)
For more Info just visit this link