MySQL - Select and Update in a single command - mysql

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.

Related

Update and select using single query in mysql

I want to update the columns and select the values using single query in MySQL
For example
update table set address='bangalore',updated_count =updated_count+1 where id=1
select * from table where id=1
This is not possible. As #D-Shih mentioned, you cannot do both update and select in the same query. The SQL update convention doesn't allow for return data and the select statement can't write to a table.
Each has its own purpose and can't be written in one statement. They must be executed separately.

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'

MySQL Update statement error

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.

MYSQL Updating multiple fields from fields of another table

Scenario:
I have an application that has a config table which stores the config data for each website thats uses the application. I have added a couple of extra columns to the config table and rolled this out to all applications. I have since updated these new columns with data that needs to be the same on all the config tables.
How would I go about doing this?
My first thought would be to duplicate the table and do the following:
UPDATE `config` SET `config`.`new1` = `tmp_config`.`new1`, `config`.`new2` = `tmp_config`.`new2` LEFT JOIN `tmp_config` ON (`tmp_config`.`tmp_id` = `config`.`id`)
Would this have the desired affect.
The following has worked for me (USING an INNER join and moving the SET to the end of the query:
UPDATE `config` INNER JOIN `tmp_config` ON (`tmp_config`.`id` = `config`.`id`)
SET `config`.`new1` = `tmp_config`.`new1`, `config`.`new2` = `tmp_config`.`new2`
Thanks for all your help!
I don't quite understand all of your question. Where have you changed the config? I read your explanations as:
You have changed the schema for all applications
You have updated the applications' configurations elsewhere
See VolkerK's answer for the correct syntax for multi-table updates.
Which storage engine are you using? If it's InnoDb (or other engine that supports transactions), you should start a transaction before running the query. Then you can verify that the result is the desired one before you commit any changes:
Example:
mysql> START TRANSACTION;
mysql> SELECT * FROM Configs LIMIT 5; -- See what it looks like before
mysql> Run update query here
mysql> SELECT * FROM Configs LIMIT 5; -- Verify that the result is the expected one
mysql> COMMIT;
This should have the effect of updating new1 and new2 in config to the values of new1 and new2 in tmp_config where ever the ids from the two tables match (and null if there is no match in tmp_config).
I believe that's what you said you are trying to do.
From the MySql update reference:
You can also perform UPDATE operations
covering multiple tables. However, you
cannot use ORDER BY or LIMIT with a
multiple-table UPDATE. The
table_references clause lists the
tables involved in the join. Its
syntax is described in Section
12.2.8.1, “JOIN Syntax”. Here is an example:
UPDATE items,month SET
items.price=month.price WHERE
items.id=month.id;
In this case they're not using just the "JOIN" syntax, but the JOIN syntax should still be valid, you just need to do it prior to the SET clause.
It would look something like
UPDATE `config`
LEFT JOIN `tmp_config` ON (`tmp_config`.`tmp_id` = `config`.`id`)
SET `config`.`new1` = `tmp_config`.`new1`, `config`.`new2` = `tmp_config`.`new2`
you need to do like :
edit
CREATE TABLE newtable SELECT * FROM oldtable;
MySQL creates new columns for all elements in the SELECT. For example:
mysql> CREATE TABLE test (a INT NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (a), KEY(b))
-> TYPE=MyISAM SELECT b,c FROM test2;
The multi-table update syntax doesn't allow a JOIN where you put it, see http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE
config, tmp_config
SET
config.new1 = tmp_config.new1,
config.new2 = tmp_config.new2
WHERE
tmp_config.tmp_id = config.idshould do the trick (untested, no warranty ;-))