Update a row and delete another one - mysql

I'm trying to update a table with values from another table. What I want to do is, each time an update happens, to delete the row in the table where I'm getting the data from.
This is my code so far:
UPDATE city SET city_longitude = (SELECT city_longitude FROM cities WHERE city.shortCity = cities.city_name OR city.cityName = cities.city_name LIMIT 1) LIMIT 100
This update is working so far, but I have to delete the rows where I'm updating FROM (the ones in the cities table).
Is there any way to do this?

delete from cities where some_id = 1
Are you unable to do something along these lines after your UPDATE statement has finished? You may want to have something that actually confirms your UPDATE statement succeeded and then only DELETE afterwards.
The safer alternative is to have a flag called isUpdated or something along those lines, which you can set to true after an UPDATE but you keep the row in the original table.

Related

Why this query is not working

I'm new to SQL so I don't understand why this this query is not working. Thank you in advance
CREATE VIEW temp AS
SELECT return_date_time, renting_date_time
FROM renting;
CREATE TRIGGER charge_calc AFTER UPDATE ON renting.return_date_time
FOR EACH ROW
BEGIN
UPDATE renting
SET new.charge =(select m.charge_per_day
from movies m,renting as r
where (m.id=r.id_movie))*datediff(temp.return_date_time,temp.renting_date_time);
END
DATA DIAGRAM
I don't think you should run the update of the charge on that way; if you're wanting to set the values of a row in a trigger that is firing because the row has been updated, all you need to do is
SET new.columnname = somevalue
To set the value of columnname on the updated row. You don't kick off another update of the table within the update trigger that is firing upon update of the table.
Next, you seem to be joining all the rows in movies together with all the rows in renting, which will surely return hundreds or thousands of rows, and you're trying to set one value. This is broken logic: which of the thousands of movie rows do you want MySQL to pick? It won't choose; the logic is broken
Step back for moment and consider: this is an update trigger of the renting table. It fires for every row updated and the row being updated is accessible by the new. specifier. There is a new.movie_id property - that's the id of the movie being updated right now. If you want some data out of the movies table, select it based on the movie id in the new row (the row being updated) I.e. new.movie_id
You don't need the temp view either - if you want to know the return date, surely that is also part of the new. row
All in, this trigger should probably be a single line along the following idea:
SET new.charge = (select rate from movies where id = new.movie_id) * datediff(date_rented, date_returned, day)
As a side comment, I think the front end app should be doing this, not triggers in the database

MySQL Update with Delete sub query

I want to do the following
Delete all the records from a table called survey and then set the status of deleted reference numbers to zero(0) which is in other table.
The query which I am using is below
Update ref_numbers rn SET rn.status = 0 where ref_no IN (DELETE FROM survey WHERE id < 302)
But this query is not working, I have also tired to modify the delete query like DELETE ref_no FROM survey...... but still it's not working. I think I am missing something which i don't know.
Any help would be highly appreciated.
You can't delete and update in the same operation. You can solve this problem better using either (1) a trigger -- maintain the reference count using an AFTER trigger on the child table, or (2) a view -- create the reference count as a correlated subquery in a view of the parent table.

MySQL delete multiple rows in one query conditions unique to each row

So I know in MySQL it's possible to insert multiple rows in one query like so:
INSERT INTO table (col1,col2) VALUES (1,2),(3,4),(5,6)
I would like to delete multiple rows in a similar way. I know it's possible to delete multiple rows based on the exact same conditions for each row, i.e.
DELETE FROM table WHERE col1='4' and col2='5'
or
DELETE FROM table WHERE col1 IN (1,2,3,4,5)
However, what if I wanted to delete multiple rows in one query, with each row having a set of conditions unique to itself? Something like this would be what I am looking for:
DELETE FROM table WHERE (col1,col2) IN (1,2),(3,4),(5,6)
Does anyone know of a way to do this? Or is it not possible?
You were very close, you can use this:
DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))
Please see this fiddle.
A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.
You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.
DELETE FROM
orders_products_history
WHERE
(branchID, action) IN (
SELECT
branchID,
action
FROM
(
SELECT
branchID,
action
FROM
orders_products_history
GROUP BY
branchID,
action
HAVING
COUNT(*) > 10000
) a
);
I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.
Hope this is of use.
Richard.
Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.
#create some empty list
values = []
#continue to append the values you want to delete to it
#BUT you must ensure instead of a string it's a single value tuple
values.append(([Your Variable],))
#Then once your array is loaded perform an execute many
cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)

Update and show mysql query

UPDATE myTable SET niceColumn=1 WHERE someVal=1;
SELECT * FROM myTable WHERE someVal=1;
Is there a way to combine these two queries into one? I mean can I run an update query and it shows the rows it updates. Because here I use "where id=1" filtering twice, I don't want this. Also I think if someVal changes before select query I will have troubles about what I get (ex: update updates it and after that someVal becomes 0 because of other script).
Wrap the two queries in a transaction with the desired ISOLATION LEVEL so that no other threads can't affect the locked rows between the update and the select.
Actually, even what you have done will not show the rows it updated, because meanwhile (after the update) some process may add/change rows.
And this will show all the records, including the ones updated yesterday :)
If I want to see exactly which rows were changed, I would go with temp table. First select into a temp table all the row IDs to be updated. Then perform the update based on the raw IDs in the temp table, and then return the temp table.
CREATE TEMPORARY TABLE to_be_updated
SELECT id
FROM myTable
WHERE someVal = 1;
UPDATE myTable
SET niceColumn = 1
WHERE id IN (SELECT * FROM to_be_updated);
SELECT *
FROM myTable
WHERE id IN (SELECT * FROM to_be_updated)
If in your real code the conditional part (where and so on) is too long to repeat, just put it in a variable that you use in both queries.
Unless you encounter a different problem, you shouldn't need these two combined.

Multiple set and where clauses in Update query in mysql

I don't think this is possible as I couldn't find anything but I thought I would check on here in case I am not searching for the correct thing.
I have a settings table in my database which has two columns. The first column is the setting name and the second column is the value.
I need to update all of these at the same time. I wanted to see if there was a way to update these values at the same time one query like the following
UPDATE table SET col1='setting name' WHERE col2='1 value' AND SET col1='another name' WHERE col2='another value';
I know the above isn't a correct SQL format but this is the sort of thing that I would like to do so was wondering if there was another way that this can be done instead of having to perform separate SQL queries for each setting I want to update.
Thanks for your help.
You can use INSERT INTO .. ON DUPLICATE KEY UPDATE to update multiple rows with different values.
You do need a unique index (like a primary key) to make the "duplicate key"-part work
Example:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE b = VALUES(b), c = VALUES(c);
-- VALUES(x) points back to the value you gave for field x
-- so for b it is 2 and 5, for c it is 3 and 6 for rows 1 and 4 respectively (if you assume that a is your unique key field)
If you have a specific case I can give you the exact query.
UPDATE table
SET col2 =
CASE col1
WHEN 'setting1'
THEN 'value'
ELSE col2
END
, SET col1 = ...
...
I decided to use multiple queries all in one go. so the code would go like
UPDATE table SET col2='value1' WHERE col1='setting1';
UPDATE table SET col2='value2' WHERE col1='setting1';
etc
etc
I've just done a test where I insert 1500 records into the database. Do it without starting a DB transaction and it took 35 seconds, blanked the database and did it again but starting a transaction first, then once the 1500th record inserted finish the transaction and the time it took was 1 second, so definetely seems like doing it in a db transaction is the way to go.
You need to run separate SQL queries and make use of Transactions if you want to run as atomic.
UPDATE table SET col1=if(col2='1 value','setting name','another name') WHERE col2='1 value' OR col2='another value'
#Frits Van Campen,
The insert into .. on duplicate works for me.
I am doing this for years when I want to update more than thousand records from an excel import.
Only problem with this trick is, when there is no record to update, instead of ignoring, this method inserts a record and on some instances it is a problem. Then I need to insert another field, then after import I have to delete all the records that has been inserted instead of update.