Reputation: 11
In a case where I have a column that needs to be unique eg. product:eggs, tomatoes, pepper, pepper1, pepper2 and before i insert another pepper i need to check the last integer, and add 1 to it, so the next pepper would be 'pepper3' How would i do this? Thanks in advance
Upvotes: 1
Views: 543
Reputation: 1854
The easy way is to have two columns: the first for the label and the second for the id. It's never good to mix up various information in the same column.
Then you could do something like :
SELECT MAX(product_id) FROM ... WHERE label = "pepper"
and
SELECT CONCAT(label,product_id) FROM ... WHERE id = ...
Returns what you want.
Upvotes: 5
Reputation: 928
I would try something like this:
SELECT LEFT(product_name, 6) AS product_name_plain,
CAST(RIGHT(product_name, 6) AS UNSIGNED) AS product_number
FROM product_table
WHERE product_name_plain = "pepper"
ORDER BY product_number DESC
LIMIT 1
SELECT
breaks apart product names into the plain name ("pepper"), and an unsigned integer version of the product number (3).WHERE
clause identifies the peppers.ORDER BY
will sort them (which should result in the last pepper being the first result)LIMIT
will only fetch the one result.Upvotes: 0