我有4个不同的表:
CONTEST有很多对象(通过contest_obj)和奖金。比赛包含开始和结束日期。
OBJECT有很多比赛(通过contest_obj)
CONTEST_OBJ包含object_id,contest_id,投票(比赛结束日期后的大多数选票都是赢家)
WINNING有contest_id,amount和amount_type(美元和欧元)
我希望能够在尽可能少的SQL调用中访问此数据。更具体地说,我目前没有存储比赛的获胜者,所以我一直在计算这个。
我希望能为SQL编写一些帮助:
代码我必须确定比赛的胜利者:
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
样本表数据:
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)
在上面的例子中:
比赛X(over)中有2个对象(foo和bar)。 Bar是Contest X的获胜者,获得12票。 Bar在此次比赛中赢得了5美元和6欧元的奖金。