I am in need to insert a row in a table if it does not exist, or update it otherwise, but based in a column that is not unique or primary.
I am doing the insert part with :
INSERT INTO table (`match`, `to`, `status`, `type`, cat, rel, tag) VALUES ('$match_tag', '$match_tag_url', '1', 'redirection', 'confirmed', '', '$tag')
but if match exists already I'd like to update the to value, all in one query if possible.
I apologise in advance for the novice question and thank everyone for any input.
I am thinking the solution might relate to the ON DUPLICATE KEY UPDATE statement, but all the examples I have found so far involve a unique or primary item which I do not have in my case.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
CREATE TABLE people (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
salary INT NOT NULL,
PRIMARY KEY (id)
);
My insert statement
INSERT INTO people
VALUES
('Austin', 65000),
('Josh', 100000),
('Pettea', 55000)
;
The columns amount (total columns amount in table structure while their list is skipped) must match the values amount strongly.
So either specify column names:
INSERT INTO people (first_name, salary)
VALUES
('Austin', 65000),
('Josh', 100000),
('Pettea', 55000);
or specify the value for each column:
INSERT INTO people
VALUES
(NULL, 'Austin', 65000),
(NULL, 'Josh', 100000),
(NULL, 'Pettea', 55000);
In the last code you may use zero value or DEFAULT keyword instead of NULL. Any of these 3 values causes new value generation.
PS. The former code is preferred - it does not need in any edition if the structure is altered.
PPS. I'd recommend to define autoincremented column datatype as UNSIGNED - this doubles the amount of possible autogenerated values twice.
It should be:
INSERT INTO people(first_name, salary)
VALUES
('Austin', 65000),
('Josh', 100000),
('Pettea', 55000);
try that.
Here's a working fiddle: https://www.db-fiddle.com/f/rW6QyPbyEMvZhcskipBpaX/0
click "Run".
Edit:
I think I misread your comment: In this case you need to specify which column(s) you want to insert data. For now your query is trying to insert a two columns data value into a three columns table. INSERT INTO people is similar to INSERT INTO people(id,first_name,salary) so inserting two columns worth of data returns Column count doesn't match value count at row 1 error. It's acceptable if you do like this:
INSERT INTO people
VALUES
(1,'Austin', 65000),
(2,'Josh', 100000),
(3,'Pettea', 55000);
But you're making id column as AUTO_INCREMENT for a reason hence it's unnecessary to manually populate it.
I have two tables in a Mysql database: "stock_pricing" and "DATA_IMPORT"
columns in first table: STOCK_ID, DATE, LAST_CLOSE_DOM_CURR
columns in second table: STOCK_ID, DATE, ADJ_CLOSE
The first table has an index on stock_id and date together. These have been defined as UNIQUE.
The second table has no index at all.
The second table has incoming data. On this table there is a BEFORE INSERT trigger that inserts incoming data into the first table.
If upon the insert trigger the combination of STOCK_ID and DATE violates the UNIQUE index of the first table, the ON DUPLICATE KEY UPDATE part of the trigger is fired.
I have tried every combination I can think of, but the trigger does not recognise my column names, any thoughts? Many thanks.
BEGIN
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
VALUES (DATA_IMPORT.STOCK_ID, DATA_IMPORT.DATE, DATA_IMPORT.ADJ_CLOSE)
ON DUPLICATE KEY UPDATE
stock_pricing.STOCK_ID= DATA_IMPORT.STOCK_ID, stock_pricing.DATE= DATA_IMPORT.DATE, stock_pricing.LAST_CLOSE_DOM_CURR= DATA_IMPORT.ADJ_CLOSE;
END
You are referencing a table called data_import with no from clause. This is fixed using insert . . . select:
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
SELECT DATA_IMPORT.STOCK_ID, DATA_IMPORT.DATE, DATA_IMPORT.ADJ_CLOSE
FROM DATA_IMPORT
ON DUPLICATE KEY UPDATE
stock_pricing.STOCK_ID= DATA_IMPORT.STOCK_ID, stock_pricing.DATE= DATA_IMPORT.DATE, stock_pricing.LAST_CLOSE_DOM_CURR= DATA_IMPORT.ADJ_CLOSE;
A more typical way of writing such a query is:
INSERT INTO stock_pricing (`STOCK_ID`, `DATE`, `LAST_CLOSE_DOM_CURR`)
SELECT di.STOCK_ID, di.DATE, di.ADJ_CLOSE
FROM DATA_IMPORT di
ON DUPLICATE KEY UPDATE STOCK_ID = VALUES(STOCK_ID),
DATE = VALUES(DATE),
LAST_CLOSE_DOM_CURR = VALUES(LAST_CLOSE_DOM_CURR);
For ON DUPLICATE KEY UPDATE to work, you need a unique index or primary key. I assume you have these.
Finally, this code looks a bit strange for a trigger, because there are no references to NEW or OLD. If you are still having trouble with the trigger, then ask another question and include the full code for the trigger.
I'm trying to set a unique restraint on a combination of columns rather than on a single column. I have a table, "tags":
id (int, PK, AI, unsigned)
tag (varchar 25)
user_id (int, unsigned)
Following the answer to this question, I tried to set the combo restraint via:
ALTER TABLE `tags` ADD UNIQUE `unique_tag_user_combo` (`tag`, `user_id`);
So far, so good. But when I come to test it, by seeing if it will let me insert the same tag twice but with different user IDs (it should), it errors:
INSERT INTO `tags` VALUES (NULL, 'foo', '1'), (NULL, 'foo', '2')
...throws...
Duplicate entry 'foo' for key 'name_2'
Remember the unique restraint is on the combo of tag + user_id, so this query, to my mind, should run fine. I could understand this error if I'd tried to insert foo/1 twice, but not foo/1 and foo/2. What am I missing?
(EDIT - also, what's that 'name_2' reference in the error message all about? I don't have a column with that name...)
You might also have an unique index on tag column.Use
SHOW CREATE TABLE yourtb
I'm pretty much a complete newbie to SQL, I'm using MySQL with SQLyog. I have five fields, StudentForename, StudentSurname, StudentAge, StudentHouse and StudentID for the Primary Key. The StudentID field is set as a Primary Key and Not Null and AutoIncrement. I'm trying to use an INSERT INTO statement without having to entering the primary key - apparently I shouldn't need to, it should update itself. But it's not working, it's returning the error "Column count doesn't match value count at row 1". Here's the code I'm using. I've already set up the table, so I haven't got the code for the query that
INSERT INTO students VALUES('Harry', 'Potter', 'Slytherin', 30)
You will need to explicitly state which columns you will provide values for, otherwise it is assumed you will provide values for all columns. E.g.
INSERT INTO students (`first_name`, `last_name`, `house`, `age`) VALUES('Harry', 'Potter', 'Slytherin', 30)
(I made up column names, swap these with your columns)
I have a table with with essentially three columns: user_id, setting, and value. I'm trying to use the following code:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 500)
ON DUPLICATE KEY UPDATE user_id = 1234, setting = setting_1'
This works great when creating a new setting, and it doen't generate duplicate records. The problem comes when I want to change the value- this won't work after the previous query has run:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 999)
ON DUPLICATE KEY UPDATE user_id = 1234, setting = setting_1'
No rows are affected. Clearly I'm missing something...
IMPORTANT: I am not able to alter the database (new primary keys or something).
UPDATE: It seems my understanding of ON DUPLICATE KEY is wrong. But the question remains- what is the most efficient way way to accomplish this?
Answered in a comment below: "If the Primary (or Unique) key is (user_id, setting), then use: ... ON DUPLICATE KEY UPDATE value=999".
Assuming you actually have a unique key on user_id, you are getting "no rows affected" because you aren't changing anything in the second query. I think what you want to do is update the value field as well:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 999)
ON DUPLICATE KEY UPDATE setting = setting_1,value=999
Without value in there, you're just setting the user_id and the setting field to the same values they were before, and MySQL doesn't need to update the record.
If you don't have a unique key on user_id, you'll have to find a different approach, as the ON DUPLICATE KEY UPDATE won't trigger.