I'm trying to do the following thing:
I have two tables: ReportImage (imageId, reportId, counter)
and userReportedImages (imageId, userId)
I want that every user will be able to report an image only once - this means that first I want to check if there is a row in 'userReportedImages' with the values (imageId, userId) if so do nothing, else create a row in 'ReportImage' with the values (imageId, reportId, counter), if such row already exist (other user reported that image) then I want to raise the counter.
so far before checking for same user report I had the following statement:
INSERT INTO ReportImage VALUES (imageId,reportId,1) ON DUPLICATE KEY UPDATE counter = counter+1
this statement is working fine.
I tried to change this statement to first check if the row exist on the other table, but I didn't manage to do it, can you help me?
First, you need to define a UNIQUE constraint or a compund column primary key on table ReportImage,
ALTER TABLE ReportImage ADD CONTRAINT tb_uq UNIQUE(ImageID, ReportID)
Give this a try,
INSERT INTO ReportImage(ImageID, ReportID, Counter)
SELECT 'imageID HERE' AS ImageID,
'userID HERE' AS ReportID,
1 AS Counter
FROM userReportedImages a
LEFT JOIN ReportImage b
ON a.imageId = b.imageId AND
a.userId = b.ReportID AND
a.imageID = 'imageID HERE' AND
a.userID = 'userID HERE'
WHERE b.imageId IS NULL OR
b.ReportID IS NULL
ON DUPLICATE KEY UPDATE counter = VALUES(counter) + 1
you could try using NOT EXISTS
insert into table2(`name`)
select * from (select 'name1' as name) tmp
where not exists(
select ('x') from table1 where name = 'test1'
);
SQL Fiddle
An insert trigger should be a solution for you: link
Related
I'm facing an issue with SQL at the moment, i have got a relation between two columns in a table like this they are linked together as an unique key (id, charid) and using that relation i want to determine if i want to insert it or not, so if the following already exists
[charid: 1, id: 1]
I want to update it instead of inserting a new row, however if we insert a row like this and charid 1, id 1 already exists, that's OK and we can insert it.
[charid: 1, id: 1]
How can i correctly do this? I heard this could be done by using restrictions with the columns.
SQL Server:
UPDATE R
SET R.COLUMN = VALUE
FROM dbo.TABLE1 AS R
INNER JOIN dbo.TABLE2 AS P
ON R.charid = P.id
**Edit, actually you need a subquery with a "WHERE EXISTS" clause. Will update in a bit.
UPDATE R
SET R.COLUMN = VALUE
FROM dbo.TABLE1 AS R
WHERE EXISTS ( SELECT P.id
FROM dbo.TABLE2 AS P
WHERE R.charid = P.id )
It turns out, when you have a primary key or two, you can do the following instead:
(Please note: You do need atleast one primary key for this)
INSERT INTO arcade (id, charid, highscore) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE highscore = ?
this makes it so that when there's a duplicate key, it updates the row instead of trying to insert something!
I have CSV files and I need to do something like this before inserting data in my table:
table fields
id = primary id and auto-increment
house_no
city_code
prv_code
cty_code
if (house_no,city_code,prv_code,cty_code) exists = ignore insert
else if (house_no,city_code,prv_code,cty_code) is null = ignore insert
else (house_no,city_code,prv_code,cty_code) !exist = insert
My original code just re-inserts the same values because the primary key id is just creating a new id for it and as a result I have duplicates.
I need to do this to avoid duplicates. I tried INSERT IGNORE and REPLACE but I need a unique key and all fields may have a value which is the same (like they may have different house_no but the same prv_code or cty_code or something like that). I just want to check if the record exist before I insert it.
You can create a unique key over more than one column. In your case you need an unique key containing of the four columns house_no, city_code, prv_code and cty_code.
In your case:
ALTER TABLE fields
ADD CONSTRAINT uc_fieldsUnique UNIQUE (house_no,city_code,prv_code, cty_code);
Load data from CSV-file into second table, and then use INSERT like this to add rows -
INSERT INTO t1(id, house_no, city_code, prv_code, cty_code)
SELECT NULL, t2.house_no, t2.city_code, t2.prv_code, t2.cty_code FROM t2
LEFT JOIN t1 ON t1.house_no = t2.house_no AND t1.city_code = t2.city_code AND t1.prv_code = t2.prv_code AND t1.cty_code = t2.cty_code
WHERE t1.id IS NULL
(rename table names)
If I'm inserting data into a table with the following fields:
serialNumber active country
I need to only insert duplicate serialNumbers if active is no.
So for example: I want to insert a record with serialNumber 1234.
If the serial number doesn't already exist in the table go ahead and add it. If it does already exist, check the value of 'active' active is yes then don't add the new record, if it's no then do add the record.
Any ideas how to achieve this in MYSQL?
If the table lacks the necessary unique keys and you do not have permission, or don't want to set the keys you would need, you can use this alternative:
INSERT INTO `table1`
(`field1`,
`field2`)
SELECT value1,
value2
FROM (SELECT 1) t_1
WHERE NOT EXISTS (SELECT 1
FROM `table1`
WHERE `field1` = value1
AND `field2` = value2);
For yor question it could be written as
INSERT INTO `activity`
(`serialNumbers`,
`active`)
SELECT 1234,
'yes'
FROM (SELECT 1) t_1
WHERE EXISTS (SELECT 1
FROM `activity`
WHERE `serialNumbers` = 1234
AND `active` = 'no');
You can use the ON DUPLICATE KEY statement after an INSERT INTO query to update the row if it already exists. Documentation : https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (serialNumber , active, country) VALUES (1010, 'no', 'FR')
ON DUPLICATE KEY UPDATE active='yes';
You can use the insert ... on duplicate key update in MySQL. It is similar to the MERGE used in other SQL databases, but MySQL does not provide the MERGE statement so this is the next best.
INSERT INTO TABLE (serialNumber, active, country)
VALUES (1234, 'active', 'GB') ON DUPLICATE KEY UPDATE country = 'ND';
Also, use INSERT IGNORE if you don't want to generate errors.
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)
How can I use a single query for inserting table when a column value is not found.
eg/ i want to insert new user only when this username not found
what i doing now is issue 1 query to check for existing,
then another query if no existing found. total 2 query
INSERT INTO friends (memberID) SELECT 1 WHERE NOT EXISTS (SELECT memberID FROM friends WHERE memberID = 1)
You just need to add FROM DUAL
INSERT INTO friends
(memberid)
SELECT 1
FROM dual
WHERE NOT EXISTS (SELECT memberid
FROM friends
WHERE memberid = 1)
sql fiddle
How about this:
INSERT INTO YourTable (UserName)
SELECT x
FROM (SELECT 'New User Name' AS x) a
WHERE x NOT IN(SELECT UserName
FROM YourTable)
Since you only want one row with a given value you should enforce that with a UNIQUE constraint on the table, for example:
ALTER TABLE friends ADD UNIQUE (memberID);
After you do that, you can simply add the IGNORE keyword to your insert statements and it won't report an error and it won't insert a duplicate row if it already exists.
INSERT IGNORE INTO friends(memberID) VALUES(1);