I have two tables like this in mysql
a.cardnumber (unique)
a.position (numerical 3 digits or null)
a.serial
b.serial (unique)
b.lastused
I want to update any rows in “a” where position is above 600 AND “a.serial” is blank with any serial from “b.serial” where “b.lastused” is either null or more than 30 days ago. When the serial is copied into “a.serial” I want to update “b.lastused” with today’s date so I know that the relevant “b.serial” has been used today.
There is no relation to the two tables apart from the serial and any serial from b can be used with any cardnumber in a.
I’ve tried this using my limited knowledge of mysql but I keep getting an error from my mysql desktop program to say I have an error in my query 🙁
Any help much appreciated!
I’m assuming here that you want to use a separate
b.serialfor each row to be updated ina. (This isn’t specifically stated, but it seems to me to be most likely; please feel free to correct my assumption if it is wrong.)I setup a small example. It wasn’t clear what the datatypes for each of the columns, so I used INT where I wasn’t sure. I used DATE datatype (rather than DATETIME) for lastused.
Based on the conditions you give, the rows with cardnumbers ‘a1111’ and ‘a2222’ should get updated, the other two rows should not (position <= 600, serial already assigned).
Before we run an UPDATE, we want to first run a SELECT that returns the rows to be updated, along with the values that will be assigned. Once we get that, we can convert that to a multi-table UPDATE statement.
To convert that to an UPDATE, replace the
SELECT ... FROMwithUPDATE, and add aSETclause to assign new values to the tables.You can run the queries for the inline views seperately (ia, jb) to verify that these are getting the rows you want to update.
The join from ia to a, and from jb to b, should be on the primary keys unique key.
The purpose of the ia and jb inline views is to get sequential numbers assigned to those rows so we can match them to each other.
The joins to
aandbare to get back to the row in the original table, which is what we want to update.(Obviously, some adjustments need to be made if
serialis not an INT, orlastusedis a DATETIME rather than a DATE.)But this is an example of how I would go about doing the UPDATE you want to do (as best I understood it.)
NOTE: This approach works with MySQL versions that support subqueries. For MySQL 4.0, you would need to run this in steps, storing the results from the “ia” and “jb” inline views (subqueries) into actual tables. Then reference those tables in the query in place of the inline views. The ii and jj subqueries can be removed, and replaced with separate
SELECT @i := 0, @j := 0statement prior to the execution of the queries that reference these variables.