문제

I've got a table booking (id, date, interval) and another table booking_data (id, date, data), so I attach data in my booking_data table on id and date because my bookings are generated automatically, so when I want to insert data to avoid double insertion I have to use one of these methods:

  1. SELECT and INSERT or UPDATE as necessary
  2. DELETE by id and date, and then INSERT
  3. REPLACE (I'm not sure about this whether has to have two keys or not and if has to have two my second can be the date.)

Which of these will be the best in my situation?

도움이 되었습니까?

해결책

Each of the possibilities has different tradeoffs, so there isn't a clear single answer. Some notes:

  1. If you use SELECT followed by INSERT or UPDATE, you will need to use transactions START TRANSACTION and COMMIT or set autocommit = 0, and then use SELECT ... FOR UPDATE otherwise you may have conflicts with other transactions. This has the advantage though that you can potentially avoid doing anything if there are no conflicts.

  2. Using DELETE followed by INSERT is manually doing exactly what REPLACE does. The REPLACE statement in a single statement and single transaction attempts to INSERT in a loop, and each time a key conflicts, it deletes the offending row. Doing this manually is more work both for you and the database and is trickier to implement correctly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top