[英]mysql select distinct where in multiple rows
考慮一個包含這兩列和值的表,zGameParticipants
GameID | ParticipantID
1 | 10
1 | 11
2 | 11
2 | 12
3 | 13
3 | 14
3 | 15
我想選擇具有ParticipantID 10和11的獨特GameID。出於顯而易見的原因,我不能這樣做
SELECT
DISTINCT GameID
FROM zGameParticipants
WHERE ParticipantID IN ($ParticipantIDs)
其中$ParticipantIDs
是具有ParticipantID的數組。
可以有n個ParticipantID,因此將n ParticipantID添加到數組並綁定為參數可能會以某種方式工作。 否則嵌套選擇可能是我正在尋找的,但我無法理解這一點。
如果所有你想要的是一個獨特的游戲,無論參與者的數量...也就是每場比賽一行
然后只需添加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
添加到@John Ruddell
例
輸入參數 :參與者ID在范圍內(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。
我相信您正在尋找具有陣列中列出的所有參與者的GameID。 (這就是為什么你不能使用你發布的SQL查詢,因為這將選擇具有任何參與者的GameID)
如果是這種情況,解決此問題的方法之一是動態生成查詢。
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.