2

I have two database tables called Item and Inspection. An Item has many inspections. Basically, an inspection is done on an item and the inspection records it's state of bring "not broken" vs. "broken". Regular inspections are made on each item.

I want to update a newly added field for each record in the Items table called "last_broken_at". It needs to be updated to the "created" datetime found in the oldest related Inspection for that Item, where the Inspection "status" field is equal to "broken".

While that is definitely possible via a single MySQL update statement, here is the caveat:

If an Item was repaired at some point and inspection found the item to be "not broken", but is then later found to be "broken" again, the Item's "last_broken_at" field must be updated to the "created" datetime of the inspection where the status was "broken" after an inspection of status "not broken".

Basically, the "last_broken_at" field in the Items table must be true to its name, it must indeed be closest time we know the Item went from being "not broken" to "broken".

Here are what the tables look like:

Items table

  • ID (INT)
  • created (DATETIME)
  • name (VARCHAR)
  • status (VARCHAR) Note: contains latest status of the item, as per the last inspection.
  • last_broken_at (DATETIME)

Inspections

  • id (INT)
  • created (DATETIME)
  • item_status (VARCHAR)
  • item_id (INT)

Thanks!!

4

1 回答 1

0

尝试:

UPDATE items t 
SET    t.last_broke_at = (
                          SELECT min(created) 
                          FROM   inspections t1 
                          WHERE  t.item_id=t1.item_id 
                             AND status='broken' 
                             AND NOT EXISTS (
                                             SELECT * 
                                             FROM   inspections t2 
                                             WHERE  t1.item_id = t2.item_id 
                                                AND t2.created> t1.created 
                                                AND t2.status = 'not broken'
                                            )
                         )
于 2012-11-03T23:06:20.000 回答