This question is further to my previous question answered very well by @ypercube here
I have been trying to work out the easiest way to ask the question without ambiguity, here I go…
I have data arriving from a sensor that contains a unique serial number and a data value. The sensor configuration along with its unique serial number is in a table called device which also contains other settings such as enabled or disabled.
I want to store the incoming data value into another table named datain along with the primary key from the device table.
I am currently doing this with several individual MySQL statements and wish to improve the efficiency by reducing it to one MySQL statement.
Steps to complete are:
- Retrieve the primary key and boolean enabled state for supplied sensor serial number from device table
- Test if primary key exists and boolean enabled value is true, if either is no, then just exit.
- If primary key exists and boolean enabled is true, then store the incoming data value and the primary key (identified by the above test) into another table named datain
Maybe below explains a little better what I am trying to do. I know this is not valid MySQL, just an example of what want.
`INSERT INTO mydb.datain(sensorpk,sensorvalue) values (pk from sensor serial in device table, 25.4) WHERE mydb.device.pk = pk from sensor serial in device table AND mydb.device.enabled = TRUE;`
Best Answer
I'm reading your question differently than Stefan did: I believe you're saying you want to issue a single SQL statement as follows:
Using Stefan's dbfiddle as a starting point, I came up with this:
My version of the dbfiddle is here; it shows four insert attempts, two for enabled devices, with one for a disabled device and one for an invalid serial # in between. Only the data for the enabled devices that exist is added.
Quick explanation of how this works: You're starting with two know values, the serial number of a device (which uniquely identifies it), and the data that should (maybe) be inserted. We're simply selecting the
device_id
from thedevice
table that matches your serial number, and is enabled. If the device matching your serial number is disabled, we'll get no rows back in theSELECT
, and nothing will be inserted; we only insert the data if we find the serial number, and the device is enabled.FYI: If you had a table with the serial numbers and device data, you could insert all the valid ones at once with: