MySQL Update subquery table is specified twice - mysql

I'm trying this subquery to decrease 1 in my quantity every time I execute this query. I think it will work on SQL-Server but why isn't it working on MySQL. I'm getting this error:
Table 't1' is specified twice, both as a target for 'UPDATE' and as a separate source for data
here's my code
Update tblbooks AS t1
set t1.Quantity = (Select t2.Quantity-1
from tblbooks AS t2
where t2.BookId = 123)
where t1.BookId = 123

You don't need the subquery there - you can reassign a calculation on a column back to the same column:
UPDATE tblbooks
SET Quantity = Quantity - 1
WHERE BookId = 123

Related

MYSQL Update Table set column equal to select column from same table

I have a new column in my database and I need fill it up with the value of the same column from one specific row. I want to create a feature "copy to all"
For example add the same price to all the products taken from the first row:
ID NAME PRICE
1 PROD1 5
2 PROD2 0
3 PROD3 0
4 PROD4 0
I am trying to select the PRICE of the first row (ID 1) and copy it to all the other rows.
I have tried:
UPDATE PRODUCTS SET PRICE = (select PRICE from PRODUCTS where ID = 1);
I want to end up with this
ID NAME PRICE
1 PROD1 5
2 PROD2 5
3 PROD3 5
4 PROD4 5
But I get this error:
Table 'PRODUCTS' is specified twice,
both as a target for 'UPDATE' and as a separate source for data
I tried specifying each table separately
UPDATE PRODUCTS as a SET a.PRICE = (select b.PRICE from PRODUCTS as b where b.ID = 1);
But I get the same error.
Table 'a' is specified twice,
both as a target for 'UPDATE' and as a separate source for data
Maybe I have to create a temporary table and copy from it?
Any hints on how to accomplish this?
Thanks.
You can do it by nesting the select query:
UPDATE PRODUCTS
SET PRICE = (
select PRICE from (select PRICE from PRODUCTS where ID = 1) t
);
See the demo.
Another way to do it, with a self CROSS JOIN:
UPDATE PRODUCTS p CROSS JOIN (
select PRICE from PRODUCTS where ID = 1
) t
SET p.PRICE = t.PRICE;
See the demo.
This wouldn't work logically, as SQL would try to fetch the data it is updating.
Try running your nested statement select PRICE from PRODUCTS where ID = 1 seperately, saving the response and then running your main statement: "UPDATE PRODUCTS SET PRICE = " + newPrice
If this is a SQL script, i suggest you to break it into 2 queries using a variable:
select #var := PRICE from PRODUCTS where ID = 1;
UPDATE PRODUCTS SET PRICE = #var;
Variables are much more easier than temporary table in my opinion.
I've not fully tested, but the syntax should be that
After looking at many answers on other posts and websites, (none of them had the precise answer), I found the solution with this query, and yes we need temp tables:
CREATE TEMPORARY TABLE tmptable SELECT ID, PRICE FROM PRODUCTS WHERE ID = 1;
UPDATE PRODUCTS SET `PRICE` = (select tmptable.`PRICE` from tmptable where tmptable.ID = 1);
BUT! #forpas solution's is really good and works without creating a temp table.
enjoy.
NEW question: is the temp table removed automatically? Leave me a comment.
Cheers

use values of two fields of a first SELECT into a second one

Let's say we have a database with a table defined by the following fields:
id -- localCode -- localNumber -- status
Hoping to help you: there will be different records with the same combination (localCode + localNumber) but different status.
I would like to use the results from this query
SELECT localCode, localNumber FROM Table WHERE status = 'val_1'
to find the records with the combination (localCode + localNumber) found before but status = 'val_2'.
Thank you all
Make a self-join on the table.
SELECT
t2.id
FROM Table t1
INNER JOIN Table t2
ON t1.localCode = t2.localCode
AND t1.localNumber = t2.localNumber
WHERE t1.status = 'val_1'
AND t2.status = 'val_2'
This query will find all IDs of records that have status val_2 and where a corresponding entry with status val_1 exists.

MySQL update column value with max value from another column

I have a database with 2 tables:
"services" and "service_performance"
Those 2 tables have a SERVICE_ID column.
In "services" the SERVICE_ID values are unique (each service has a single ID/entry).
In "service_performance" there is an AVERAGE_MEMORY column with multiple entries per service_id
I am trying to update the MAX_VALUE column in "services" table with the highest AVERAGE_MEMORY value taken from the "service_performance" table.
I know my query is wrong because it throws an error:
1054 - Unknown column 'service_performance.SERVICE_ID' in 'where clause'
While 'service_performance.SERVICE_ID' does exist.
Here is my query:
update _services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID FROM service_performance)
where exists
(select *
from services
where `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`);
You should find that this version works in MySQL:
update services s join
(select service_id, MAX(AVERAGE_MEMORY) as maxmem
from service_performance
group by service_id
) sp
on s.service_id = sp.service_id
set s.MAX_VALUE = sp.maxmem;
Your version would work if it had the right table name in the where clauses:
update services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID
FROM service_performance
WHERE `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`)
where exists (select *
from service_performance
where `services`.`SERVICE_ID` = `service_performance`.`SERVICE_ID`
);
I am assuming that update _services is a typo and should really be update services.
MySQL is complaining because in this query there is no service_performance table
Try it like this:
UPDATE _services s INNER JOIN service_performance p
ON s.SERVICE_ID=p.SERVICE_ID
SET s.MAX_VALUE=MAX(p.AVERAGE_MEMORY) GROUP BY p.SERVICE_ID
I don't have a database to test on, but firstly you haven't given the subquery an alias, so it doesn't know what service_performance.Service_ID is.
Secondly, in this context the subquery needs to return a single value rather than a table, so you may not be able to reference it. If adding the alias to the subquery doesn't work, then something like the following should work:
update _services
set MAX_VALUE = (SELECT MAX(AVERAGE_MEMORY) AS SERVICE_ID FROM service_performance
INNER JOIN
services
on services.SERVICE_ID = service_performance.SERVICE_ID)

Complicated MySql Update Join Query

Have is an example of the problem I'm facing. The database tables are a little different than usual, but needed to be setup this way.
Items: id, order_id, other fields
Items_Drinks: id, drinks, other fields
Orders: id, other fields
Orders_Drinks: id, drinks, other fields
I need to have an update query that will update the Orders_Drinks table with the sum of the Items_Drinks drinks field that have the same order_id as Orders_Drinks id field.
Items: 1 1 ...
Items: 2 1 ...
Items_Drinks: 1 4 ...
Items_Drinks: 2 5 ...
Orders: 1 ...
Orders_Drinks: 1 9 ...
The Orders_Drinks is currently correct, but if I were to update Items_Drinks with id of 1 to 5, I would need an update command to get Orders_Drinks with id 1 to equal 10.
It would be best if the command would update every record of the Orders_Drinks.
I know my database is not typical, but it is needed for my application. This is because the Drinks table is not needed for all entries. The Drinks table has over 5000 fields in it, so if every record had these details the database would grow and slow for no real reason. Please do not tell me to restructure the database, this is needed.
I am currently using for loops in my C# program to do what I need, but having 1 command would save a ton of time!
Here is my best attempt, but it gives an error of "invalid group function".
update Orders_Drinks join Items on Items.order_id=Orders_Drinks.id join Items_Drinks on Items_Drinks.id=Items.id set Orders_Drinks.drinks=sum(Item_Drinks.drinks);
I think this is what you're wanting.
Edited:
UPDATE `Order_Drinks` a
SET a.`drinks` = (SELECT SUM(b.`drinks`) FROM `Items_Drinks` b INNER JOIN `Items` c ON (b.`id` = c.`id`) WHERE a.`id` = c.`order_id`)
That should give you a total of 9 for the Order_Drinks table for the row id of 1.
This is assuming that Orders.id == Orders_Drinks.id and that Items.id == Items_Drinks.id.
You need to do an aggregation. You can do this in the join part of the update statement:
update Orders_Drinks od join
(select i.order_id, sum(id.drinks) as sumdrinks
from Items i join
Items_Drinks id
on id.id = i.id
) iid
on iid.order_id = od.id
set od.drinks = iid.sumdrinks;
Something like this will return the id from the orders_drinks table, along with the current value of the drinks summary field, and a new summary value derived from the related items_drinks tables.
(Absent the name of the foreign key column, I've assumed the foreign key column names are of the pattern: "referenced_table_id" )
SELECT od.id
, od.drinks AS old_drinks
, IFNULL(td.tot_drinks,0) AS new_drinks
FROM orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
Once we have SELECT query written that gets the result we want, we can change it into an UPDATE statement. Just replace SELECT ... FROM with the UPDATE keyword, and add a SET clause, to assign/replace the value to the drinks column.
e.g.
UPDATE orders_drinks od
LEFT
JOIN ( SELECT di.orders_drinks_id
, SUM(di.drinks) AS tot_drinks
FROM items_drinks di
GROUP BY di.orders_drinks_id
) td
ON td.orders_drinks_id = od.id
SET od.drinks = IFNULL(td.tot_drinks,0)
(NOTE: the IFNULL function is optional. I just used it to substitute a value of zero whenever there are no matching rows in items_drinks found, or whenever the total is NULL.)
This will update all rows (that need to be updated) in the orders_drinks table. A WHERE clause could be added (after the SET clause), if you only wanted to update particular rows in orders_drinks, rather than all rows:
WHERE od.id = 1
Again, to get to this, first get a SELECT statement working to return the new value to be assigned to the column, along with the key of the table to be updated. Once that is working, convert it into an UPDATE statement, moving the expression that returns the new value down to a SET clause.

MySQL sub query select statement inside Update query

I have 2 tables: tbl_taxclasses, tbl_taxclasses_regions
This is a one to many relationship, where the main record ID is classid.
I have a column inside the first table called regionscount
So, I create a Tax Class, in table 1. Then I add regions/states in table 2, assigning the classid to each region.
I perform a SELECT statement to count the regions with that same classid, and then I perform an UPDATE statement on tbl_taxclasses with that number. I update the regionscount column.
This means I'm writing 2 queries. Which is fine, but I was wondering if there was a way to do a SELECT statement inside the UPDATE statement, like this:
UPDATE `tbl_taxclasses` SET `regionscount` = [SELECT COUNT(regionsid) FROM `tbl_taxclasses_regions` WHERE classid = 1] WHERE classid = 1
I'm reaching here, since I'm not sure how robust MySQL is, but I do have the latest version, as of today. (5.5.15)
You could use a non-correlated subquery to do the work for you:
UPDATE
tbl_taxclasses c
INNER JOIN (
SELECT
COUNT(regionsid) AS n
FROM
tbl_taxclasses_regions
GROUP BY
classid
) r USING(classid)
SET
c.regionscount = r.n
WHERE
c.classid = 1
Turns out I was actually guessing right.
This works:
UPDATE `tbl_taxclasses`
SET `regionscount` = (
SELECT COUNT(regionsid) AS `num`
FROM `tbl_taxclasses_regions`
WHERE classid = 1)
WHERE classid = 1 LIMIT 1
I just needed to replace my brackets [] with parenthesis ().