Here are two possible approaches, at the database level, depending on your needs:
If there's a reason to store a record in the database for every occurrence of a Person/Fruit (i.e. You need to save the time the fruit was eaten, etc.), then there is no reason to store the rank value in the database, as that would require an UPDATE
with each INSERT
. You can get the rank with a simple query using COUNT(*)
.
If there is no reason to store every occurrence, then you should have only one entry per Person/Fruit combination with a rank value which is updated on every subsequent occurrence.
Rank Retrieved with Aggregate Function
Query to get the rank: (Assuming every occurrence is stored in Person_Fruit table)
SELECT person, fruit, COUNT(*)
FROM person_fruit
WHERE person = 'the_person'
AND fruit = 'the_fruit'
GROUP BY 1, 2;
Rank Stored in Database
Assuming table Fruits (id, person, fruit, rank), with a multi-column index on person and fruit, so you have only one occurrence of each unique combination.
Prior to INSERT
/UPDATE
, check if Person/Fruit already exists:
SELECT id
FROM fruits
WHERE name = 'the_name' AND fruit = 'the_fruit';
If it doesn't, INSERT
Person/Fruit with rank value of 1
, as this is the first occurrence:
INSERT INTO fruits (id, person, fruit, rank)
VALUES (NULL, 'the_person', 'the_fruit', 1); /* NULL should be replaced by auto-generated value, if set up for that */
If it does, UPDATE
the rank:
UPDATE fruits
SET rank = rank +1
WHERE id = id /* You can use id returned from previous `SELECT`, or Person AND Fruit */