2014-11-05 32 views
0

我有四个表:如何创建这样的查询?

  • 锦标赛(ID,姓名,插槽,价格,游戏ID,platformId)
  • 游戏(ID,姓名)
  • 平台(ID,姓名)
  • 参股( id,tournamentId,playerId)

我想得到锦标赛的游戏名称,平台名称,插槽,价格,reservedSlots(参与计数),某些玩家(他的id是否由php提供)在本次比赛(布尔/真)和条件是: - 游戏ID必须是由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) 
+0

什么不行?错误日志?查询是否在mysql工作台中工作,即查询是否有效 – ChelseaStats 2014-11-05 08:15:00

+1

什么是错误的?你没有输出,或输出错误? – Gudgip 2014-11-05 08:15:11

+0

有输出,但它不是我想要的。它返回尽可能多的记录,因为参与者存在参与 – Lukas 2014-11-05 08:24:22

回答

1

我不会dwelve成H andling您的文章,并获得价值,我会认为一切都正常:

$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注入。

+0

我认为这就是我所寻找的;)我只添加了一个条件来获得只开放的比赛,但谢谢你回答, 问题解决了。 – Lukas 2014-11-05 08:54:05

+0

@Lukas,我很高兴能帮上忙。如果我的答案解决了这个问题,那么你可以考虑接受它作为正确的答案。 – 2014-11-05 12:05:30