SELECT MAX(col) FROM tableA gives you the maximum value in column
col from table
I think what you're asking to do is:
$val(a value from somewhere — presumably your PHP) is larger than 0 and smaller than the maximum value stored in the table
tableA, then ensure that the value appears in the table
If so, you might be able to use:
INSERT INTO tableB(col) SELECT $val FROM dual WHERE $val > 0 AND $val < (SELECT MAX(col) FROM tableA) AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val)
You now need to translate that into appropriate PHP.
(See also MySQL conditional insert.)
How can I add ON DUPLICATE KEY to my query?
Also you can remove the
AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val)because
colis unique and it prevents inserting duplicate.
You don't need the ON DUPLICATE because the NOT EXISTS makes it irrelevant. And if you don't mind the error from an attempted duplicate insertion, you don't need any of this: you just do
INSERT INTO tablaB(col) VALUES(?).
AFAICS, the ON DUPLICATE clause does a no-op UPDATE; this avoids the need to do that. I suppose it wouldn't be a no-op if there are triggers on the table such that the 'last modified' (time, or user, or both) columns will be changed, or if the key of the table isn't the
col column — these are pretty esoteric possibilities, though. You could have helped by showing an outline schema of the table indicating such features.
If you really need the ON DUPLICATE clause, you can read the manual as well as I can and add it after the SELECT.
INSERT INTO tableB(col) SELECT $val FROM dual WHERE $val > 0 AND $val < (SELECT MAX(col) FROM tableA) AND NOT EXISTS(SELECT col FROM tableB WHERE col = $val) ON DUPLICATE KEY UPDATE col = VALUE(col)
(And, of course, if you really don't want the NOT EXISTS clause, you can remove it.)