I have 4 different tables:
- Contest
- Object
- Contest_Obj
- Winning
CONTEST has many objects (through contest_obj) AND winnings. A contest contains start and end dates.
OBJECT has many contests (through contest_obj)
CONTEST_OBJ contains object_id, contest_id, votes (most votes after end date of contest is a winner)
WINNING has contest_id, amount, and amount_type (dollars and euros)
I would like to be able to access this data in as few SQL calls as possible. More specifically, I am not currently storing the winner of a contest, so I have been calculating this on the fly.
I was hoping to get some help writing the SQL for:
- total_winning_dollars (return total dollars won in past contests)
- total_winning_euros (return total dollars won in past contests)
- all_won_contests (return all contests that object is the winner along with winnings for that contest as both dollars and euros)
Code I have to determine winner of a contest:
SELECT "objects".*
FROM "objects"
INNER JOIN "contest_objs" ON "objects"."id" = "contest_objs"."object_id"
WHERE "contest_objs"."contest_id" = ?
ORDER BY votes DESC
LIMIT 1
sample table data:
CREATE TABLE `contests` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`start_date` DATETIME,
`end_date` DATETIME,
`user_id` INT,
`title` STRING
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE `objects` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` STRING
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE `winnings` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`contest_id` INT NOT NULL,
`comment` TEXT,
`amount_type` STRING NOT NULL,
`amount` INT NOT NULL,
`user_id` DATETIME
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE `contest_objs` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`contest_id` INT NOT NULL,
`object_id` INT NOT NULL,
`votes` INT
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `objects` VALUES
(1, "Foo"),
(2, "Bar")
INSERT INTO `contests` VALUES
(1, "2012-09-16 23:30:16.220991", "2012-09-17 23:30:16.220991", 1, "Contest X"),
(2, "2012-09-17 23:30:16.220991", "2016-09-17 23:30:16.220991", 2, "Contest Y")
INSERT INTO `winnings` VALUES
(1, 1, "Giving $5", 5, "dollars", 1),
(2, 1, "Giving 2 euros", 2, "euros", 1),
(3, 1, "Giving 4 euros", 4, "euros", 2),
(4, 2, "Giving 2 euros to different contest", 2, "euros", 1)
INSERT INTO `contest_objs` VALUES
(1, 1, 1, 10),
(2, 1, 2, 12),
(3, 2, 2, 0),
(4, 2, 2, 0)
In the above example:
Contest X (over) has 2 objects in it (foo and bar). Bar is the winner of Contest X with 12 votes. Bar has won $5 dollars and 6 euros total from this contest.