MySQL Update statement error - mysql

I have two scripts, one for the Insert, and another for Update.
My update button script is using the latest inserted Id, and goes on something like this:
Update tblsurvey
set WouldLikeToBeSeenOnSite = 'sadffas'
and DislikedOnSite = 'asdfsadfsadf'
and OtherNewsWebsitesRead = 'asdfsadfa'
and LikedOnOtherNewsSites = 'asdfsadfas'
and IPAddress = '172.16.0.123'
and DateAnswered = current_date()
where SurveyResponseId in (select max(SurveyResponseId) from tblsurvey);
Apparently, the "where" clause generates an error:
1093 - you cant specify target table 'tblsurvey' for update in FROM clause.
Is there any other way in which i could use the latest inserted ID of the same table i am updating?
Thanks.

wait a second. why are you using AND to delimit SET claus elements? it must be comma separated.

you cannot use the same table (in this case, table tblsurvey) for both the subquery FROM clause and the update target.
Its illegal to use same table for updating/deleting and subquery for UPDATE and DELETE operations.

Related

You can't specify target table 'finansal' for update in FROM clause error (!)

When I execute this
DELETE FROM finansal WHERE idfinansal=(SELECT MAX(idfinansal) FROM finansal);
I have this error.
You can't specify target table 'finansal' for update in FROM clause
How do I delete the last record on Workbench?
You may try wrapping the max subquery in another subquery as a workaround:
DELETE
FROM finansal WHERE idfinansal =
(SELECT max_fin FROM
(SELECT MAX(idfinansal) AS max_fin FROM finansal) x );
This subquery trick forces MySQL to materialize the max subquery before running the actual delete statement. The same approach can be used for other DML operations, such as update.

Check if record exists delete it using mysql

i'm using MySQL and i want to check if a record exists and if it exists delete this record.
i try this but it 's not working for me:
SELECT 'Barcelone' AS City, EXISTS(SELECT 1 FROM mytable WHERE City = 'Barcelone') AS 'exists';
THEN
DELETE FROM mytable
WHERE City = 'Barcelone';
Thank you for your help.
The if statement is only allowed in stored procedures, stored functions, and triggers (in MySQL).
If I understand what you want, just do:
DELETE FROM mytable
WHERE City = 'Barcelone';
There is no reason to check for the existence beforehand. Just delete the row. If none exist, no problem. No errors.
I would recommend an index on mytable(city) for performance reasons. If you want to check if the row exists first, that is fine, but it is unnecessary for the delete.
If you mean MySQL is returning an error message (if that's what you mean by "not working for me"), then that's exactly the behavior we would expect.
That SQL syntax is not valid for MySQL.
If you want to delete rows from a table, issue a DELETE statement, e.g.
DELETE FROM mytable WHERE City = 'Barcelone'
If you want to know how many rows were deleted (if the statement doesn't throw an error), immediately follow the DELETE statement (in the same session) with a query:
SELECT ROW_COUNT()
Or the appropriate function in whatever client library you are using.
If the ROW_COUNT() function returns 0, then there were no rows deleted.
There's really no point (in terms of MySQL) in issuing a SELECT to find out if there are rows to be deleted; the DELETE statement itself will figure it out.
If for some reason your use case requires you to check whether there are rows be be deleted, then just run a separate SELECT:
SELECT COUNT(1) FROM mytable WHERE City = 'Barcelone'

Does mysql UPDATE inserts the values if it doesn't exist?

UPDATE items SET name = 'haha' WHERE id = '12'
I'm curious if update also inserts the values if the where condition fails. I've read on w3schools that update only updates existing data on the database but on my script it's automatically inserting rows with the data. I am wondering if it might be a bug in the script or that's just how UPDATE works on mysql.
No. If, in your example, there's no entry with id = 12 in the database, the query will return "no rows affected". An update will never create a new entry in MySQL.
EDIT: although update won't create a new entry, it may include default/automatic values set up in your database schema (current timestamp, for instance).
NO. Update does not insert a value if the value doesn't exist in table. Please check if the script checks if the status of the update and makes another call to DB to insert the data.
Your SQL should do the following -
Update all records in the items table that have an id of 12 by setting their name to 'haha'
Update won't insert records if they don't exist, it will only update existing records in the table.
Short answer: No.
Long Answer: If your column doesn't exist you will get an error. If your where condition column doesn't exist you get error too. If your where condition value doesn't exist, it do nothing.
I use a temp table to review the data update conditions, you can refer
UPDATE table1
SET
column1 = 'things'
WHERE
IDcolumn = 'id' AND
(NOT EXISTS (SELECT * FROM (SELECT * FROM table1) AS temp WHERE temp.column1 = N'things'))

MySQL - Select and Update in a single command

I need to select a transactionID from a MySQL table and immediately increment it.
SELECT transid FROM idtable;
UPDATE idtable SET transid=transid +1;
I would like to combine the queries but cannot get the correct syntax.
Using a WHERE clause in your UPDATE will have the same effect.
UPDATE table
SET column = column + 1
WHERE column = value
You could use a sub-query style approach, but I have to wonder if there's any need for the initial SELECT. (Can't you just use a WHERE clause on the UPDATE, perhaps involving a multiple table join if so required.)
Take a look at the MySQL UPDATE query syntax for more information.

How to select and update a record at the same time in mySQL?

Is there any way to select a record and update it in a single query?
I tried this:
UPDATE arrc_Voucher
SET ActivatedDT = now()
WHERE (SELECT VoucherNbr, VoucherID
FROM arrc_Voucher
WHERE ActivatedDT IS NULL
AND BalanceInit IS NULL
AND TypeFlag = 'V'
LIMIT 1 )
which I hoped would run the select query and grab the first record that matches the where clause, the update the ActivatedDT field in that record, but I got the following error:
1241 - Operand should contain 1 column(s)
Any ideas?
How about:
UPDATE arrc_Voucher
SET ActivatedDT = NOW()
WHERE ActivatedDT IS NULL
AND BalanceInit IS NULL
AND TypeFlag = 'V'
LIMIT 1;
From the MySQL API documentation :
UPDATE returns the number of rows that were actually changed
You cannot select a row and update it at the same time, you will need to perform two queries to achieve it; fetch your record, then update it.
If you are worrying about concurrent processes accessing the same row through some kind of race condition (supposing your use case involve high traffic), you may consider other alternatives such as locking the table (note that other processes will need to recover--retry--if the table is locked while accessing it)
Or if you can create stored procedure, you may want to read this article or the MySQL API documentation.
But about 99% of the time, this is not necessary and the two queries will execute without any problem.