2017-04-09 141 views
0

我正在查找一個SQL查詢,該查詢選擇列最終只有唯一值的x行。從2列中選擇唯一值

表被稱爲keezdrives_played 列被稱爲:TEAM_ID和opponents_id

[1]

這是應該如何像[數據庫的圖片。]: [實施例] [2]

凡TEAM_ID和opponents_id具有唯一值

+0

使用不同(oppnents_id) –

回答

0

你可以用這樣的查詢做到這一點:

SELECT t.team_id ,o.opponents_id FROM yourTAble t 
INNER JOIN (
    SELECT team_id,opponents_id FROM yourTAble 
    GROUP BY opponents_id 
    HAVING count(*) = 1 
) AS o ON o.team_id = t.team_id 
GROUP BY t.team_id 
HAVING count(*) = 1; 

樣品

mysql> select * from yourTable; 
+---------+--------------+ 
| team_id | opponents_id | 
+---------+--------------+ 
|  1 |   5 | 
|  1 |   6 | 
|  2 |   7 | 
|  2 |   80 | 
|  3 |   9 | 
|  4 |   11 | 
|  4 |   22 | 
|  8 |   5 | 
+---------+--------------+ 
8 rows in set (0,00 sec) 

mysql>  SELECT t.team_id ,o.opponents_id FROM yourTAble t 
    ->  INNER JOIN (
    ->   SELECT team_id,opponents_id FROM yourTAble 
    ->   GROUP BY opponents_id 
    ->   HAVING count(*) = 1 
    -> ) AS o ON o.team_id = t.team_id 
    ->  GROUP BY t.team_id 
    ->  HAVING count(*) = 1; 
+---------+--------------+ 
| team_id | opponents_id | 
+---------+--------------+ 
|  3 |   9 | 
+---------+--------------+ 
1 row in set (0,00 sec) 

mysql> 

見註釋

mysql> SELECT count(*) AS cnt , team_id 
    -> FROM keezdrives_played 
    -> GROUP BY team_id 
    -> ; 
+-----+---------+ 
| cnt | team_id | 
+-----+---------+ 
| 4 | 2281 | 
| 4 | 2282 | 
| 4 | 2283 | 
| 4 | 2284 | 
| 4 | 2285 | 
| 4 | 2286 | 
+-----+---------+ 
6 rows in set (0,00 sec) 

mysql> 

一個嘗試更多

SELECT team_id,opponents_id 
FROM keezdrives_played 
GROUP BY CONCAT(team_id, '-', opponents_id) 
HAVING count(*) = 1; 

最後嘗試

SELECT * FROM (
    SELECT t.team_id ,t.opponents_id 
    FROM keezdrives_played t 
    GROUP BY t.team_id 
    ) r 
GROUP BY r.opponents_id; 
+0

發表您的示例表作爲SQL轉儲,以幫助您 –

+0

我有我的答案添加。你會發現team_id不是唯一的。有4行,每行enty –

+0

的還是你尋找一個獨特的組合只有這兩個領域的 –

0

我希望這是你想要的

SELECT DISTINCT team_id ,opponents_id FROM keezdrives_played where drive_id=144; 
+0

你做這個兩步。這是第一步,然後第二步是不同的第一步結果,然後獲得結果。出於這個原因,你必須需要子查詢。 –

+0

我希望如果你使用子查詢,那麼你得到適當的結果 –