SELECT DISTINCT返回重复值

时间:2012-12-12 01:48:58

标签: mysql sql

我有3张牌players positions players_national

我需要SELECT DISTINCT players_national个位置,其中player_positon与players表相关联。

我的表格是这样的:

Players Table
-----------------------------------------------------------------------
| player_id         player_name     player_team     player_position   |
-----------------------------------------------------------------------
    1               KAKA                12              1
    2               Ronaldo             7               2
    3               Adriano             10              2



Positions Table
-------------------------------------------------------
| position_id         position_name                   |
-------------------------------------------------------
     1                  Midfield            
     2                  Forward         



Players_national Table
-------------------------------------------------------------------
| player_id             player_team         player_national_team  |
-------------------------------------------------------------------
     1                       12                         4
     2                       7                          4
     3                       19                         4

My Dream output is this
---------------------------------------------------
| player_national_team          position          |
---------------------------------------------------
          4                         1                           
          4                         2                           

我的查询是这样的:

SELECT DISTINCT players. * , positions. * , players_national. * 
FROM players
LEFT JOIN positions ON positions.position_id = players.player_position
LEFT JOIN players_national ON players_national.player_id = players.player_id
WHERE players_national.player_id = players.player_id AND players_national.player_national_team = 4

2 个答案:

答案 0 :(得分:1)

如果您从每个表格中选择所有内容,那么每一行都将为DISTINCT;您需要将SELECT子句限制为您想要的字段DISTINCT

SELECT DISTINCT positions.position_id, players_national.player_national_team
FROM            players
                LEFT JOIN positions ON positions.position_id = players.player_position
                LEFT JOIN players_national ON players_national.player_id = players.player_id
WHERE           players_national.player_id = players.player_id AND players_national.player_national_team = 4

答案 1 :(得分:0)


桌面玩家的独特player_position,其中加入table players_national

SELECT 
  DISTINCT(players.player_position),
  players_national.player_national_team
FROM players INNER JOIN players_national;

结果:

+-----------------+----------------------+
| player_position | player_national_team |
+-----------------+----------------------+
|               1 |                    4 |
|               2 |                    4 |
+-----------------+----------------------+
2 rows in set