简体   繁体   中英

MySQL - update the row with the highest start date

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
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM