I have a system where users can earn 1 or more credits for different types of contributions. These are stored within 2 tables:
CREATE TABLE user_contribution_types (
type_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
credits DECIMAL(5,2) UNSIGNED NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
PRIMARY KEY (type_id)
);
CREATE TABLE user_contributions (
user_id INTEGER UNSIGNED NOT NULL,
type_id INTEGER UNSIGNED NOT NULL,
create_date DATETIME NOT NULL,
valid TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
FOREIGN KEY (user_id)
REFERENCES users(user_id),
FOREIGN KEY (type_id)
REFERENCES user_contribution_types(type_id)
);
I can select the total credits earned since a specific date with the following:
SELECT SUM(credits) AS total
FROM user_contribution_types AS a
JOIN user_contributions AS b ON a.type_id = b.type_id
WHERE b.create_date >= '2017-05-01 00:00:00'
AND a.valid = TRUE
AND b.valid = TRUE
Likewise, I could include a match for b.user_id
to find the total credits for that specific user.
What I would like to do is treat each credit earned as an entry into a giveaway, and select 3 random (unique) user_id
s from the total. So if one user has earned 26 credits, they will have 26 chances to win.
How can this be done with SQL, or would it make more sense to do it at the application level? I would prefer a solution that is as close to truly random as possible.