如何创建这样的查询?

时间:2014-11-05 08:12:18

标签: php mysql

我有四张桌子:

  • 锦标赛(id,name,slots,price,gameId,platformId)
  • 游戏(身份证,姓名)
  • 平台(id,name)
  • 参与(id,tournamentId,playerId)

我想获得锦标赛的游戏名称,平台名称,位置,价格,reservedSlots(参与计数),是否某些玩家(他的id由php提供)参与此锦标赛(bool / true)的信息,条件是: - gameId必须在php提供的指定数组中 - platformId必须在php提供的指定数组中

我创建了类似的东西,但它无法正常工作:

PHP:

$platformsList = "'". implode("', '", $platforms) ."'"; // 
$gamesList = "'". implode("', '", $games). "'"; 

MySQL的:

    SELECT
    t. NAME AS tournamentName,
    t.id,
    t.slots,
    p. NAME,
    g. NAME AS gameName,
    t.price
FROM
    tournaments AS t,
    platforms AS p,
    games AS g,
    participations AS part
WHERE
    t.PlatformId = p.Id
AND t.GameId = g.Id
AND t.Slots - (
    SELECT
        count(*)
    FROM
        participations
    WHERE
        TournamentId = t.id
) > 0
AND part.TournamentId = t.Id
AND t.PlatformId IN ($platformsList)
AND t.GameId IN ($gamesList)

1 个答案:

答案 0 :(得分:1)

我不会喜欢处理你的帖子并获得价值观,我会认为一切都很好:

$possibleGameIDs = getPossibleGameIDs(); //function will return the array you need for possible game id values. Inside your function make sure that the id values are really numeric
$possiblePlatformIDs = getPossiblePlatformIDs(); //function will return the array you need for possible platform id values. Inside your function make sure that the id values are really numeric
$playerId = getPlayerId(); //function returns the player id and makes sure that it is really a number

$sql = "select games.name, platforms.name, tournaments.slots, tournaments.price, ".
       "(select count(*) from participations where participations.tournamentId = tournaments.tournamentId) as reservedSlots, ".
       "(select count(*) > 0 from participations where participations.tournamentId = tournaments.tournamentId and playerId = ".$playerId.") as isParticipating ".
       "from tournamens ".
       "join games ".
       "on tournaments.gameId = games.id ".
       "join platforms ".
       "on tournaments.platformId = platforms.id ".
       "where games.id in (".implode(",", $possibleGameIDs).") and ".
       "      platforms.id in (".implode(",", $possiblePlatformIDs).") and ".
       "      tournaments.slots > 0"

代码未经过测试,如果您在使用它时遇到任何问题,请告诉我。当然你需要运行它,但是因为你没有指定你用什么来运行查询,所以我没有分配时间来处理运行它的技术细节。但请注意SQL注入。