mysql选择distinct在多行中的哪个位置

时间:2014-12-02 22:08:41

标签: php mysql

考虑一个表,zGameParticipants,这两列和值为

GameID | ParticipantID
1      | 10
1      | 11
2      | 11
2      | 12
3      | 13
3      | 14
3      | 15

我想选择具有ParticipantID 10 AND 11的独特GameID。出于显而易见的原因,我不能这样做

SELECT 
DISTINCT GameID
FROM zGameParticipants
WHERE ParticipantID IN ($ParticipantIDs)

其中$ParticipantIDs是包含ParticipantID的数组。

可以有n个ParticipantID,因此将n ParticipantID添加到数组并绑定为参数可能会以某种方式工作。否则嵌套选择可能是我正在寻找的,但我无法理解这一点。

3 个答案:

答案 0 :(得分:2)

如果您想要的只是一个独特的游戏,无论参与者数量是多少......也就是每场游戏一行

然后只需添加GROUP BY GameID

这假设$ ParticipantIDs是一个逗号分隔的列表,如此

SELECT GameID
FROM zGameParticipants
WHERE ParticipantID IN (13,14,15)
GROUP BY GameID

如果您不知道如何使其成为逗号分隔列表,那么在php中使用implode就像这样

$commaList = implode(', ', $ParticipantIDs);

然后你可以把它放在你的查询中

SELECT GameID
FROM zGameParticipants
WHERE ParticipantID IN ($commaList)
GROUP BY GameID

我建议你研究一下参数化查询,然后将参数绑定到IN()语句

编辑:

从您的评论中看起来您希望所有参与者都在游戏中返回该行。要做到这一点你可以做这样的事情

$counter = count($ParticipantIDs);
$commaList = implode(', ', $ParticipantIDs);

SELECT GameID
FROM zGameParticipants
WHERE ParticipantID IN ($commaList)
GROUP BY GameID
HAVING COUNT(DISTINCT ParticipantID) = $counter

答案 1 :(得分:1)

添加到@John Ruddell

实施例

  

输入参数:范围内的ParticipantID(13,14,15)

SELECT GameID
FROM zGameParticipants
WHERE ParticipantID IN (13,14,15)
GROUP BY GameID
HAVING COUNT(DISTINCT ParticipantID) = 3 // here count of ParticipantID`s range

我添加了HAVING=3,因为它保证GameID有13 AND 14 AND 15.

答案 2 :(得分:0)

我相信您正在寻找具有 ALL 数组中列出的参与者的GameID。 (这就是为什么你不能使用你发布的SQL查询,因为这将选择 ANY 参与者的GameIDs)

如果是这种情况,解决此问题的方法之一就是动态生成查询。

$ParticipantIDs = array(10,11,12,13,14,15);
$selectClause = "SELECT 
DISTINCT Table0.GameID\n";
$joinClauses = "";
$whereClauses = "WHERE\n";
$i = 0;
foreach($ParticipantIDs as $participantID)
{
    if ($i == 0)
    {
        $joinClauses .= "FROM zGameParticipants AS Table$i\n";
    }
    else
    {
        $joinClauses .= "INNER JOIN zGameParticipants AS Table$i ON Table".($i-1).".GameID = Table".$i.".GameID\n";
    }

    $whereClauses .= "Table$i.ParticipantID = $participantID\n";

    $i++;
}
print $selectClause.$joinClauses.$whereClauses;

这会生成此查询:

SELECT 
DISTINCT Table0.GameID
FROM zGameParticipants AS Table0
INNER JOIN zGameParticipants AS Table1 ON Table0.GameID = Table1.GameID
INNER JOIN zGameParticipants AS Table2 ON Table1.GameID = Table2.GameID
INNER JOIN zGameParticipants AS Table3 ON Table2.GameID = Table3.GameID
INNER JOIN zGameParticipants AS Table4 ON Table3.GameID = Table4.GameID
INNER JOIN zGameParticipants AS Table5 ON Table4.GameID = Table5.GameID
WHERE
Table0.ParticipantID = 10
Table1.ParticipantID = 11
Table2.ParticipantID = 12
Table3.ParticipantID = 13
Table4.ParticipantID = 14
Table5.ParticipantID = 15