简体   繁体   中英

SQL Query, insert a max value from another table's column

I have two tables, a booking table and an invoice table. I am trying to update the booking table with booking information and get a max value from the invoice table and insert it into the booking table at the same time.

So far I have this, but it doesn't set any values to the Booking.Invoice_id column

      INSERT INTO Booking( user_id, Location_id, Accom_Id,StartDate,EndDate,
          Vehreg,PartySize,Invoice_id )
      VALUES ('$User_id', '$pitch', '$Accom' , '$start',
          '$end','$Vreg','$guests','SELECT Max Invoice_id FROM Invoice;');

any help would be much appreciated

Use insert . . . select insert . . . select insert . . . select :

  INSERT INTO Booking(user_id, Location_id, Accom_Id, StartDate, EndDate,
                      Vehreg, PartySize, Invoice_id )
     SELECT '$User_id', '$pitch', '$Accom' , '$start', 
            '$end', '$Vreg', ' $guests',
            MAX(Invoice_ID)
     FROM Invoice;

My guess, however, is that you want to run this immediately after inserting a row into Invoice . In that case, you should be using LAST_INSERT_ID() .

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