0

我有一个网站,访问者可以在其中创建“战斗”并上传视频以参与这些战斗。

以下 mySQL 查询试图检索数据库中每个“战斗”的详细信息。

我遇到的问题是,如果“战斗创建者”将两个“视频”上传到同一场战斗,则会打印出重复的战斗。

即使视频表在同一个battle_id下有两个条目,如何让查询只为每场战斗打印一个值?

谢谢!

SELECT * from Battles, Player, Video 
WHERE (Battles.battle_creator = Player.player_id 
AND Battles.battle_id = Video.battle_id 
AND Video.player_id = Battles.battle_creator) 
ORDER BY Battles.battle_date DESC;
4

4 回答 4

1

一旦单个用户将多个视频分配给战斗,就无法从单个查询中获取您要求的信息。

获取战斗中所有数据的最佳方法是将查询分成两个子查询:

SELECT * from Battles, Player 
WHERE Battles.battle_creator = Player.player_id
ORDER BY Battles.battle_date DESC;

...进而:

SELECT * from Video 
ORDER BY Battles.battle_date DESC, Player.player_id;

第一个查询将为您每场战斗提供一行;第二个将为您提供所有战斗的所有视频,您可以对其进行迭代。

从扩展的角度来看,您最好完全避免 JOIN,因此额外的工作将非常值得。

于 2012-10-20T20:53:21.517 回答
0

您可以将 LIMIT 1 子句添加到查询中以仅获得第一个结果,或者使用 DISTINCT 子句,例如

SELECT DISTINCT *
FROM ...

也就是说,在查询多个表时不应使用“SELECT *” - 更具体地使用“SELECT table.*”或“SELECT table.field1, table.field2, ...”。

于 2012-10-20T20:45:05.780 回答
0

您不能“完全”这样做,因为您的查询:

SELECT * from Battles, Player, Video  ...

隐含地要求所有视频。所以你需要先问问自己,我如何选择我想要的那个视频?

如果您只想要一个视频,无论如何,然后添加LIMIT 1到查询并完成它。ORDER BYvideo_date ASC 或 DESC 之前LIMIT检索最早或最新的视频。

否则,您必须执行以下操作:

SELECT * from Battles
    JOIN Player ON (Battles.battle_creator = Player.player_id)
    JOIN Video  ON (Battles.battle_id = Video.battle_id 
                    AND Video.player_id = Battles.battle_creator)
WHERE Video.video_id = (SELECT MIN(video_id) FROM Video AS Video2 WHERE
               Battles.battle_id = Video2.battle_id 
               AND Video2.player_id = Battles.battle_creator)
ORDER BY Battles.battle_date DESC;

在上面的示例中,我使用了“video_id 最小的视频”作为“视频选择标准”。您将希望在 (Video.video_id) 上有一个索引,例如

CREATE INDEX video_ndx ON Video(player_id, battle_id, video_id);
于 2012-10-20T21:02:57.410 回答
-1

正如 Ninsuo 的评论所指出的,控制这种情况的正确方法是,在您的 ORDER BY 子句之后,指定 LIMIT 1。

如果您想要整个表,这将不起作用,只是没有重复。考虑对返回的数据运行一些比较检查,或使用 SELECT DISTINCT。

于 2012-10-20T20:43:34.310 回答