mysql query does not work - mysql

i want to set query if row not exist
IF NOT EXISTS (SELECT id FROM table WHERE id=1)
INSERT INTO table (id, name) VALUES (1,'abx');
and that if id!=1 then values are inserted and Check if row already exists
if any solution ?
thanks in advance ...
finally i soved it
INSERT INTO table (id, name) VALUES (1,'abx') ON DUPLICATE KEY UPDATE id = 1;
thanks for your suport

You have problem with data types - in SELECT id is compared to number (id = 1 - without apostrophes) and in INSERT id is written as a string (in apostrophes: '1').

INSERT IGNORE INTO `table_name` (`id`, `name`)
VALUES (1, 'abx');

MySQL does not have "IF NOT EXISTS".
For more info: How to 'insert if not exists' in MySQL?
You'll see that there are workarounds, but using MsSQL syntax won't work.
Using IGNORE should help: INSERT IGNORE INTO
Alternatively, simply let it fail.

I think that:
INSERT IGNORE INTO table (id, name) VALUES (1,'abx');
does that you want. It'll fail silently if the INSERT was unsuccessful.
Note that the key doesn't need quotes, it's an integer, not a string

Related

how to insert values in table2 with reference of table 1

I am trying to write a query to insert values in table2 with reference to table1 using a foreign key.table2 columns are (quesid(primary key/auto-increment), ques,ques_desc). There is another table table1 its primary key is foreign key which is also AUTO INCREMENT. So using that i was trying to insert values.
I have written below query:
insert into users_ques values("What is JAVA","Please SHare the details")
from users WHERE quesid = 1;
mysql is giving me error at WHERE (where is not valid at this position).
please help me so that i can sucessfully write this query.
The correct way to use select for insert
insert into users_ques (column1,column2)
select column1,column2
from users
where quesid = 1;
That is not a valid MySQL INSERT syntax. You either do:
INSERT INTO users_ques
VALUES ("What is JAVA","Please SHare the details");
OR
INSERT INTO users_ques
SELECT "What is JAVA","Please SHare the details" FROM users WHERE quesid = 1;
The way you're doing it now is just combining the two method together.
Demo fiddle

Can't insert data when use foreign key together with trigger in Mariadb [duplicate]

So I read the other posts but this question is unique. So this SQL dump file has this as the last entry.
INSERT INTO `wp_posts` VALUES(2781, 3, '2013-01-04 17:24:19', '2013-01-05 00:24:19'.
I'm trying to insert this value to the table...
INSERT INTO `wp_posts` VALUES(5, 5, '2005-04-11 09:54:35', '2005-04-11 17:54:35'
it gives me the error, "Column count doesn't match value count at row 1." So I'm lost on the concept of how the column and row apply here.
Doesn't 2781,3 mean row 2781 and column 3? And doesn't 5,5 mean row 5 and column 5?
The error means that you are providing not as much data as the table wp_posts does contain columns. And now the DB engine does not know in which columns to put your data.
To overcome this you must provide the names of the columns you want to fill. Example:
insert into wp_posts (column_name1, column_name2)
values (1, 3)
Look up the table definition and see which columns you want to fill.
And insert means you are inserting a new record. You are not modifying an existing one. Use update for that.
you missed the comma between two values or column name
you put extra values or an extra column name
You should also look at new triggers.
MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:
use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;
delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row
begin
insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//
/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');
MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
You can resolve the error by providing the column names you are affecting.
> INSERT INTO table_name (column1,column2,column3)
`VALUES(50,'Jon Snow','Eye');`
please note that the semi colon should be added only after the statement providing values
In my case i just passed the wrong name table, so mysql couldn't find the right columns names.

"INSERT IF NOT EXISTS", ELSE UPDATE certain columns in MySQL

I'm using MySQL Workbench (6.3) and I'm trying to create a stored procedure with a specific "INSERT IF NOT EXSISTS" but I think I don't do it well. By the way, I did read this topic http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html and tried both examples, it didn't work. Here is the statement :
CREATE DEFINER=`test`#`localhost` PROCEDURE `onPlayerJoin`(
IN uuid CHAR(36),
IN nickname CHAR(16),
IN firstConnection TIMESTAMP,
IN lastConnection TIMESTAMP
)
BEGIN
INSERT IGNORE INTO `test`.`player` (`playerUuid`, `playerNickname`, `playerFirstConnection`, `playerLastConnection`)
VALUES (uuid, nickname, firstConnection, lastConnection);
UPDATE `test`.`player` SET
`playerNickname` = nickname,
`playerLastConnection` = lastConnection
WHERE `playerUuid` = uuid;
END
IF the PK isn't found, INSERT it. ELSE, UPDATE certain columns. (that I can specified) However, it seems that it updates every column, which I would like to restrict to certain columns. Here is my procedure : http://pastebin.com/NfcdU9Rb !
Optional question : is it injection-safe ?
Use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Kindly refer the link for details:
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

MySQL insert - for each row, return insert id

Let's say I have an array of data to insert. I'm going to have an insert that looks like this:
INSERT INTO `table` (`name`, `value`) VALUES('name1','value1'),('name2','value2')
We're assuming that table has a primary key.
Is there a way to, while batch inserting like this, grab the last insert id for each row, and return the those new ids? I know you can't do this traditionally with LAST_INSERT_ID(), but I'm wondering if I could use something like a cursor to achieve this functionality, and maybe a temporary table to store the values until I return them.
Any help would be great.
https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
LAST_INSERT_ID() will return the first id from a multi row insert.
So you can just return that value and:
INSERT INTO `table1` (`name`, `value`) VALUES('name1','value1'),('name2','value2');
SET #firstid := LAST_INSERT_ID();
SELECT * from table1 where id>=#firstid;

Insert new row unless ONE of the values matches another row?

I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE