How to I can create a query for update, if select result is bigger then 0, else execute insert?
I had try execute this code, but is not work
select
case
where count(id) > 0 (update product set description = 'blablabla' where id_fk1 = 3 AND id_fk2 = 4)
else (insert into product (description) values('blablabla')
end
I know this is a select code, it will not work, but I don't know how to use If in mysql
you can use this example foreign-keys
there is a way to compose single query which compose single query with 'update ...' and 'insert into...'
or, if i misunderstood you, you can use this one insert-on-duplucate
What you need is INSERT with ON DUPLICATE KEY UPDATE clause:
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
This has been asked before:
Insert into a MySQL table or update if exists
Contains many interesting answers.
Presumably, you want to insert the paid id = 3, description = 'blablabla' into the table. If it exists, then update the description.
You can use insert . . . on duplicate key insert, assuming that id is declared as the primary key or as a unique key. You would do this as:
create unique key product_id on product(id);
Then the following statement does what you want:
insert into product(id, description)
select 3, 'blablabla'
on duplicate key insert description = values(description);
EDIT:
I think the same idea applies to two foreign keys:
create unique key product_fk1_fk2 on product(id_fk1, id_fk2);
insert into product(id_fk1, id_fk2, description)
select 3, 4, 'blablabla'
on duplicate key insert description = values(description);
It will be base on the number of your query result, right?
$result=mysqli_query($con,"SELECT * FROM product");
if(mysqli_num_rows($result)==0){
mysqli_query($con,"INSERT INTO product (description) VALUES ('blah')");
}
else {
mysqli_query($con,"UPDATE product SET description='blah'");
}
If you're trying to base it on your id field, try this:
$result=mysqli_query($con,"SELECT * FROM product");
if(mysqli_num_rows($result)==0){
mysqli_query($con,"INSERT INTO product (description) VALUES ('blah')");
}
else
while($row=mysqli_fetch_array($result)){
$id=$row['id'];
if($id>0){
mysqli_query($con,"UPDATE product SET description='blah' WHERE id='$id'");
}
} /* END OF WHILE LOOP */
} /* END OF ELSE */
Related
I have a table computer, which has the following columns:
computer(computer_id(pk), office_id, computer_name, login, date, time)
I am trying to create a mysql statement that will update a row if the office_id and the computer_name already exist and will insert a new row if it does not exist. I want to to still insert a new row if the office_id is different but the computer_name already exist and vise versa. If someone can give me some advice on it. I would very much appreciate it.
You can use mysql's on duplicate key update functionality to accomplish this.
Assuming you have a unique constraint on (computer_name, office_id), the following query will insert a new row in the able for new pairs of (computer_name, office_id), otherwise update the existing row:
insert into computer (office_id, computer_name, login, `date`, `time`) values
(..., ..., ..., ..., ...)
on duplicate key update login = values(login), `date` = values(`date`);
^^^^^^^^^^^^^^^^^^^^^ here is how you specify which values to update
see it in action here
Try adding UNIQUE office_id and computer_name to the Table.
an after that ....
//INSERT statement
$stmt = "INSERT IGNORE INTO table";
if ($conn->query($stmt) === false) {
die("Database error:".$conn->error);
}
// Check for success
if (affected_rows == 0) {
UPDATE TABLE
} else {
//Success and return new id
INSERT IN TO TABLE
}
My question is. I have the table 'popular' with fields 'id', 'title', 'popularity' in MySQL. I need insert info into field "title", if info not exists or increment value of 'popularity', if info exists. What is the best practice to do it?
INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO popular (title, popularity) VALUES (:the_title, 1)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), popularity = popularity + 1
Make sure you have an unique constraint on title
id = LAST_INSERT_ID(id) allows you to get the id of the record you inserted/updated using LAST_INSERT_ID (or the equivalent function for your MySQL API). If you don't need the id you can remove it from the UPDATE list.
sample code:
if exists (select * from contact where name = #name) then
select -1;
else
insert into contact(name) values(#name);
select last_insert_id();
end if;
reference:
http://ask.sqlservercentral.com/questions/88038/best-mysql-practice-to-insert-a-record-if-it-does.html
http://bugs.mysql.com/bug.php?id=19243
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
In mysql, I have the following:
Structure Table:
id(int primary key)
name(varchar 100 unique)
Values:
id name
1 test
2 test1
I have two queries:
1) SELECT count(*) FROM Table WHERE name='test'
2) if count select rows == 0 second query INSERT INTO Table (name) VALUES ('test')
I know that may be use:
$res = mysql(SELECT count(*) as count FROM Table WHERE name='test');
// where mysql function make query in db
$i = $res -> fetch_assoc();
if($i['count'] < 1 ){$res = mysql(INSERT INTO Table (name) VALUES ('test');}
But I would like know how to make two query in one query.
How do I make one query inside of two?
You can do it with a simple trick, like this:
insert into Table1(name)
select 'test' from dual
where not exists(select 1 from Table1 where name='test');
This will even work if you do not have a primary key on this column.
Explanation: DUAL is a special dummy table that is only referenced here to enable the WHERE clause. You would not be able to have a statement without a FROM clause (like select 'test' where not exists(select 1 from Table1 where name='test')) as it will be incomplete.
Assuming your name column has a UNIQUE constraint, just add IGNORE to the INSERT statement.
INSERT IGNORE INTO Table (name) VALUES ('test')
This will skip the insertion if a record already exists for a particular value and return 0 affected rows. Note that a primary key is also considered a UNIQUE constraint.
If the name column doesn't have such a constraint, I would advice that you add one:
ALTER TABLE `Table` ADD UNIQUE(name)
See also the documentation for INSERT
If you don't need to check whether there is duplication, other's suggestion is good for you. But you need, use 'INSERT' and check error number like this:
mysql_query('INSERT INTO ...');
if (mysql_errno() == 1062)
{
echo "duplicated";
}
else
{
echo "inserted";
}
(I know mysql_XXXX() is deprecated.. just example)
I have a table that looks like this:
Number | Name
--------+--------
123 | Robert
This is what I want to do:
If the Number is already in the database, don't insert a new record.
If the Number is not in the databse, but the name is, create a new name and insert it. So for example, if I have a record that contains 123 for Number and Bob for Name, I don't want to insert it, but if I get a record that contains 456 for Number and Robert for name, I would insert 456 and Robert1. I was going to check for duplicates individually like:
SELECT * FROM Person where Number = 123;
//If number is not found
SELECT * FROM Person where Name = 'Robert';
//If name is found, add a number to it.
Is there a way I can combine the two statements?
There are actually two problems in your question. The first problem is to make Number column unique and the second one is to increment the column Name by appending a number if it already exists.
FIRST PART
Since the number is UNIQUE, enforce a UNIQUE constraint on the column. It could be a PRIMARY KEY or a UNIQUE KEY.
If the column has no KEY and you want to make it PRIMARY, here is the ALTER statement:
ALTER TABLE TableName ADD CONSTRAINT tb_pk PRIMARY KEY (Number)
SQLFiddle Demo
but if you only want it to be UNIQUE and not a primary key,
ALTER TABLE TableName ADD CONSTRAINT tb_uq UNIQUE (Number)
SQLFiddle Demo
SECOND PART
You can actually do it without using join.
INSERT INTO TableName(Number, Name)
SELECT 124 AS Number,
CONCAT('Robert', COALESCE(MAX(CAST(REPLACE(Name, 'Robert', '0') AS UNSIGNED)) + 1,'')) AS Name
FROM TableName
WHERE Name LIKE 'Robert%'
SQLFiddle Demo
SQLFiddle Demo (added more example)
SQLFiddle Demo (throws exception due to uniqueness)
Some details:
when the value supplied on column Number already exists, it will throw an error since the column is unique. I have read a comment from a deleted posts saying: "..Number is not unique, but if it does exist, I don't want to enter a record." -- it does not make any sense if you don't want to add uniqueness on the column. How will you know if the number already exists or not? Doing a little check for the existence of Number feels like a little overhead for me. So my best recommendation is to enforce uniqueness.
SELECT * FROM Person WHERE Number = 123 OR Name = 'Robert'
I haven't worked with SQL for some time, so this may be wrong ;)
Edit:
$number = 123;
$name = 'Robert';
$query = mysql_query("SELECT * FROM Person WHERE Number = $number OR Name = '$name' ");
if (mysql_num_rows($query) == 0 ) {
//-> Add your record, it's unused
} else if (mysql_result($query, 0, 'number') == $number && mysql_result($query, 0, 'name' == $name)) {
//combination of number and name already exists -> modify name and add record
} else {
echo "Number is used by another name";
}
Use this query, for insert the row [123, 'Robert']. if you want insert other values, change 123 & Robert values in below query:
insert into Person (Number,Name)
select 123, IF(mn.MaxNumber is NULL,'Robert',concat('Robert',mn.MaxNumber+1))
from (SELECT 'foo') foo
left JOIN (select max(CONVERT(SUBSTR(Name,LENGTH('Robert')+1),UNSIGNED)) `MaxNumber`
from person where name rlike '^Robert[0-9]*$') mn on 1=1
where Not Exists (select * from Person where Number=123)
NOTE: if Robert exists in the table, above query inserts Robert1. if Robert1 exists, it inserts Robert2, and so on .
make both number and name unique.
ALTER TABLE `person` ADD UNIQUE (`number` ,`name`);
You can now do a insert with ON DUPLICATE
INSERT INTO `person` (`number`, `name`, `id`) VALUES ('322', 'robert', 'NULL') ON DUPLICATE KEY UPDATE `id`='NULL';
For appending a number after name i would suggest using autoincrement column instead.
insert into Person (Number,Name)
select 123, IF(mn.MaxNumber is NULL,'Robert',concat('Robert',mn.MaxNumber+1))
from (SELECT 'foo') foo
left JOIN (select max(CONVERT(SUBSTR(Name,LENGTH('Robert')+1),UNSIGNED)) `MaxNumber`
from person where name rlike '^Robert[0-9]*$') mn on true
where Not Exists (select * from Person where Number=123)
I have the following query (user_id isn't and can't be primary key as there are many entries from each user depending on another column of the table). I used duplicate key but doesnt work. It still adds a new row. Any thoughts?
INSERT INTO profile (user_id, correct) VALUES(". $user_id . ", correct + 1)
ON DUPLICATE KEY UPDATE correct=correct+1
EDIT
So if row exists for this user_id, I want to go update this entry and SET correct = correct+1 and not make a new entry with user_id and correct=1 again
Try this:
INSERT IGNORE INTO profile (user_id, correct)
VALUES ($user_id, 0);
UPDATE profile SET correct = correct + 1
WHERE user_id = $user_id; -- updates 0 to 1
Or:
UPDATE profile SET correct = correct + 1
WHERE user_id = $user_id;
If not found:
INSERT INTO profile (user_id, correct)
VALUES ($user_id, 1);
I prefer the second variant.
The first variant requires that the user_id has a UNIQUE constraint. (PRIMARY KEY counts.)