MySQL - update the row with the highest start date - mysql

I am trying to update the member row with the highest start date using:
UPDATE at_section_details a
SET a.sd_end_date = ?
, a.sd_details = ?
WHERE a.cd_id = ?
AND a.sd_start_date = (SELECT MAX(b.sd_start_date)
FROM at_section_details b
WHERE b.cd_id = ?)
The error message is:
"SQLException in updateYMGroup: java.sql.SQLException: You can't specify target table 'a' for update in FROM clause
The table structure is:
sd_id - primary key
cd_id - foreign key (many occurrences)
sd_section
sd_pack
sd_start_date
sd_end_date
sd_details
A member (cd_id) can start and then transfer out.
The member can then transfer in again (new start date). When they transfer out we want to pick up the max start date to transfer out against.
Any assistance would be greatly appreciated.
Regards,
Glyn

You should be able to use the LIMIT statement with an ORDER BY. Something along these lines:
UPDATE at_section_details a
SET a.sd_end_date=?, a.sd_details=?
WHERE a.cd_id=?
ORDER BY a.sd_start_date DESC
LIMIT 1

As it says on this post MySQL Error 1093 - Can't specify target table for update in FROM clause
In My SQL you can't have an update with the same table you are updating inside a subquery.
I would try to change your sub query to some like this
(Select x.* from (select max...) as x)
Sorry for abbreviating the code, I'm on mobile.

This query should work:
UPDATE at_section_details
JOIN (
SELECT cd_id, MAX(sd_start_date) sd_start_date
FROM at_section_details
WHERE cd_id = ?
GROUP BY cd_id
) AS t2 USING (cd_id, sd_start_date)
SET sd_end_date=?, sd_details=?;
See this SQL Fiddle for an example

You can try this mate:
UPDATE at_section_details SET sd_end_date = <input>, sd_details = <input>
WHERE cd_id IN (
SELECT cd_id FROM at_section_details
WHERE cd_id = <input>
ORDER BY sd_start_date DESC
LIMIT 1
);

Related

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)

Combine Update and Select Query

I got two MySQL working fine and i'm trying to find a way to combine them into one single query.
First, it selects ID of an employee.
SELECT 'ID' FROM `employee` ORDER BY ID DESC LIMIT 1;
Let's say it returns ID 100;
Then update data of employees whose ID is 100
UPDATE 'LOG' SET `TIME_EXIT`='2013/02/22' WHERE `ID`='100';
Can i do it all in a single query?
Just add them together:
UPDATE LOG SET TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM employee
ORDER BY ID DESC
LIMIT
);
But based on that code currently it'll only ever update the last employee, you will need to select the correct employee by using some other identifier to ensure you have the correct one.
UPDATE LOG SET TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM employee
WHERE NAME = 'JOHN SMITH'
ORDER BY ID DESC
LIMIT 1
);
It's now a few months old, but maybe helps you or others finding this via google…
If you want to UPDATE a field in the same selected table use this:
UPDATE LOG SET
TIME_EXIT = '2013/02/22'
WHERE ID = (
SELECT ID
FROM (
SELECT ID
FROM LOG
WHERE whatEverYouWantToCheck = whateverYouNeed
) AS innerResult
)
So, you SELECT id from a subselect. If you try to subselect it directly, mySQL quites with your error message You can't specify target table 'log' for update in FROM clause, but this way you hide your subsubquery in a subquery and that seems to be fine. Don't forget the AS innerResult to avoid getting the error message #1248 - Every derived table must have its own alias. Also match the subsubquery field name to the subquery field name in case you do something like SELECT COUNT(*) or SELECT CONCAT('#', ID)

subquery in where clause of UPDATE statement

I have the database of ATM card in which there are fields account_no,card_no,is_blocked,is_activated,issue_date
Fields account number and card numbers are not unique as old card will be expired and marked as is_block=Y and another record with same card number ,account number will be inserted into new row with is_blocked=N . Now i need to update is_blocked/is_activated with help of issue_date i.e
UPDATE card_info set is_blocked='Y' where card_no='6396163270002509'
AND opening_date=(SELECT MAX(opening_date) FROM card_info WHERE card_no='6396163270002509')
but is doesn't allow me to do so
it throws following error
1093 - You can't specify target table 'card_info' for update in FROM clause
Try this instead:
UPDATE card_info ci
INNER JOIN
(
SELECT card_no, MAX(opening_date) MaxOpeningDate
FROM card_info
GROUP BY card_no
) cm ON ci.card_no = cm.card_no AND ci.opening_date = cm.MaxOpeningDate
SET ci.is_blocked='Y'
WHERE ci.card_no = '6396163270002509'
That's one of those stupid limitations of the MySQL parser. The usual way to solve this is to use a JOIN query as Mahmoud has shown.
The (at least to me) surprising part is that it really seems a parser problem, not a problem of the engine itself because if you wrap the sub-select into a derived table, this does work:
UPDATE card_info
SET is_blocked='Y'
WHERE card_no = '6396163270002509'
AND opening_date = ( select max_date
from (
SELECT MAX(opening_date) as_max_date
FROM card_info
WHERE card_no='6396163270002509') t
)

MySQL #1093 - You can't specify target table 'giveaways' for update in FROM clause

I tried:
UPDATE giveaways SET winner = '1' WHERE ID = (SELECT MAX(ID) FROM giveaways)
But it gives:
#1093 - You can't specify target table 'giveaways' for update in FROM clause
This article seems relevant but I can't adapt it to my query. How can I get it to work?
Based on the information in the article you linked to this should work:
update giveaways set winner='1'
where Id = (select Id from (select max(Id) as id from giveaways) as t)
This is because your update could be cyclical... what if updating that record causes something to happen which made the WHERE condition FALSE? You know that isn't the case, but the engine doesn't. There also could be opposing locks on the table in the operation.
I would think you could do it like this (untested):
UPDATE
giveaways
SET
winner = '1'
ORDER BY
id DESC
LIMIT 1
Read more
update giveaways set winner=1
where Id = (select*from (select max(Id)from giveaways)as t)
create table GIVEAWAYS_NEW as(select*from giveaways);
update giveaways set winner=1
where Id=(select max(Id)from GIVEAWAYS_NEW);
Make use of TEMP TABLE:
as follows:
UPDATE TABLE_NAME SET TABLE_NAME.IsActive=TRUE
WHERE TABLE_NAME.Id IN (
SELECT Id
FROM TEMPDATA
);
CREATE TEMPORARY TABLE TEMPDATA
SELECT MAX(TABLE_NAME.Id) as Id
FROM TABLE_NAME
GROUP BY TABLE_NAME.IncidentId;
SELECT * FROM TEMPDATA;
DROP TABLE TEMPDATA;
You can create a view of the subquery first and update/delete selecting from the view instead..
Just remember to drop the view after.

Update with SELECT and group without GROUP BY

I have a table like this (MySQL 5.0.x, MyISAM):
response{id, title, status, ...} (status: 1 new, 3 multi)
I would like to update the status from new (status=1) to multi (status=3) of all the responses if at least 20 have the same title.
I have this one, but it does not work :
UPDATE response SET status = 3 WHERE status = 1 AND title IN (
SELECT title FROM (
SELECT DISTINCT(r.title) FROM response r WHERE EXISTS (
SELECT 1 FROM response spam WHERE spam.title = r.title LIMIT 20, 1)
)
as u)
Please note:
I do the nested select to avoid the famous You can't specify target table 'response' for update in FROM clause
I cannot use GROUP BY for performance reasons. The query cost with a solution using LIMIT is way better (but it is less readable).
EDIT:
It is possible to do SELECT FROM an UPDATE target in MySQL. See solution here
The issue is on the data selected which is totaly wrong.
The only solution I found which works is with a GROUP BY:
UPDATE response SET status = 3
WHERE status = 1 AND title IN (SELECT title
FROM (SELECT title
FROM response
GROUP BY title
HAVING COUNT(1) >= 20)
as derived_response)
Thanks for your help! :)
MySQL doesn't like it when you try to UPDATE and SELECT from the same table in one query. It has to do with locking priorities, etc.
Here's how I would solve this problem:
SELECT CONCAT('UPDATE response SET status = 3 ',
'WHERE status = 1 AND title = ', QUOTE(title), ';') AS sql
FROM response
GROUP BY title
HAVING COUNT(*) >= 20;
This query produces a series of UPDATE statements, with the quoted titles that deserve to be updated embedded. Capture the result and run it as an SQL script.
I understand that GROUP BY in MySQL often incurs a temporary table, and this can be costly. But is that a deal-breaker? How frequently do you need to run this query? Besides, any other solutions are likely to require a temporary table too.
I can think of one way to solve this problem without using GROUP BY:
CREATE TEMPORARY TABLE titlecount (c INTEGER, title VARCHAR(100) PRIMARY KEY);
INSERT INTO titlecount (c, title)
SELECT 1, title FROM response
ON DUPLICATE KEY UPDATE c = c+1;
UPDATE response JOIN titlecount USING (title)
SET response.status = 3
WHERE response.status = 1 AND titlecount.c >= 20;
But this also uses a temporary table, which is why you try to avoid using GROUP BY in the first place.
I would write something straightforward like below
UPDATE `response`, (
SELECT title, count(title) as count from `response`
WHERE status = 1
GROUP BY title
) AS tmp
SET response.status = 3
WHERE status = 1 AND response.title = tmp.title AND count >= 20;
Is using GROUP BY really that slow ? The solution you tried to implement looks like requesting again and again on the same table and should be way slower than using GROUP BY if it worked.
This is a funny peculiarity with MySQL - I can't think of a way to do it in a single statement (GROUP BY or no GROUP BY).
You could select the appropriate response rows into a temporary table first then do the update by selecting from that temp table.
you'll have to use a temporary table:
create temporary table r_update (title varchar(10));
insert r_update
select title
from response
group
by title
having count(*) < 20;
update response r
left outer
join r_update ru
on ru.title = r.title
set status = case when ru.title is null then 3 else 1;