0

我有 4 个不同的表:

  1. 比赛
  2. 目的
  3. 竞赛_Obj
  4. 获胜

CONTEST 有很多对象(通过比赛obj)和奖金。比赛包含开始日期和结束日期。

OBJECT 有很多比赛(通过比赛_obj)

CONTEST_OBJ 包含 object_id、competition_id、投票(比赛结束日期后的投票最多为获胜者)

WINNING 有竞赛 ID、金额和金额类型(美元和欧元)


我希望能够在尽可能少的 SQL 调用中访问这些数据。更具体地说,我目前没有存储比赛的获胜者,所以我一直在计算这个。

我希望在编写 SQL 时获得一些帮助:

  1. total_winning_dollars(返回过去比赛中赢得的总美元)
  2. total_winning_euros(返回过去比赛中赢得的总美元)
  3. all_won_contests(以美元和欧元的形式返回该对象是获胜者的所有比赛以及该比赛的奖金)

我必须确定比赛获胜者的代码:

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(结束)中有 2 个对象(foo 和 bar)。Bar 以 12 票获得竞赛 X 的获胜者。Bar 在这次比赛中总共赢得了 5 美元和 6 欧元。

4

0 回答 0