I was thinking about implementing a state table in MySQL for several Bash scripts to poll. The idea is that script #n is cleared to run once script #n-1 has finished running and has written its state and status into the state table in a MySQL db. Basically the state table would look like:
+----+-------+--------+
| id | state | status |
+----+-------+--------+
| 44 | 2 | OK |
| 45 | 3 | OK |
| .. | ... | ... |
| 55 | 2 | OK |
+----+-------+--------+
The id column is auto_increment so that can be used to define the last row.
At the moment I’ve come up with:
#!/bin/bash
#...
VARIABLE=$(mysql mydbname --skip-column-names -s --local -e \
"SELECT count(*) \
FROM statetable \
WHERE state=2 AND \
status='OK' AND \
id=(SELECT MAX(id) FROM statetable)")
if [ $VARIABLE -eq 1 ] ; then #...
Is there a right way to check if the last row in the table has the wanted state value and status pair (2 and OK in the example above) without a subquery and to pass that information to the Bash script?
ADDED SOLUTION:
#!/bin/bash
function check_state () {
VARIABLE=$(mysql mydbname --skip-column-names -s --local -e \
"SELECT (state=2) && (status='OK') \
FROM statetable \
ORDER BY id DESC \
LIMIT 1;")
return $VARIABLE
}
if ! check_state ; then #...
In MySQL, you can select not only fields, but also expressions and operations on them. Somewhat surprisingly this works for logical tests as well, the kind we use, for example in a
whereclause. That means that you could use the following SQL to get a boolean (0 / 1) result:You can try it out on this SQL Fiddle.
Sorry that I did not understand the question at first, but as it seems everybody did 🙂
The query you have written will most likely always return a value of 1, because it does not select the maximum id, it selects the number of rows with a maximum id, and if there is at least one row in the table, there is such a thing as a maximum id 🙂Assuming that you need the last ID, a better way (without a subquery) would be to order the data, and just take the first row, something like: