我有两个具有多对多关系的表(玩家和组)和一个联结表(player_group):
表“玩家”
表“ player_group”
一个玩家可以属于多个组,一个组可以具有多个玩家。用户也可以是用标志“ flg_admin”表示的组的管理员。
我想针对特定玩家建立一个告诉我的查询(让我说id1 = 27的玩家1):
因此对于player1(ID = 27),结果将是:
|group_name|no. members|flg_admin|
----------------------------------
|GROUP A | 2 | 1|
|GROUP B | 3 | 0|
我尝试了以下方法:
SELECT g.name, COUNT(x.id_player) as num_players, x.flg_admin
FROM player_group x
JOIN group g ON x.id_group=g.id
WHERE id_group IN (
SELECT
id_group
FROM player_group
WHERE id_player=27)
GROUP BY id_group;
但是通过此查询,我得到以下结果:
|group_name|no. members|flg_admin|
----------------------------------
|GROUP A | 2 | 1|
|GROUP B | 3 | 1|
对于GROUP B,flg_admin设置为1,但是如上图所示,该播放器不是GROUP B的管理员。 数小时以来,我一直在努力解决这个问题,但无济于事,我非常感谢您对此查询的任何帮助。
答案 0 :(得分:2)
x.flg_admin
并非来自所选玩家的表行,而是来自组中任意行。
您需要两次与player_group
表联接,以便从正确的行中获取此列。
SELECT g.name, COUNT(*) as num_players, y.flg_admin
FROM player_group x
JOIN `group` g ON x.id_group=g.id
JOIN player_group y ON y.id_group = x.id_group
WHERE y.id_player = 27
GROUP BY x.id_group
顺便说一句,您不应使用group
作为表名或列名,因为它是保留关键字。
答案 1 :(得分:0)
类似的东西:
SELECT g.name AS group_name
, (SELECT count(*) FROM player_group AS px WHERE px.id_group = pg.id_group) AS "no. members"
, flg_admin
FROM players AS p
JOIN player_group AS pg on p.id = pg.id_player
JOIN "group" AS g on pg.id_group = g.id
WHERE p.username = 'player1';
也许。
答案 2 :(得分:0)
我使用子查询的替代解决方案:
select tgrp.name, mgrp.members, pgrp.flg_admin
from player_group pgrp
join `group` tgrp on pgrp.id_group=tgrp.id
join (
select id_group, count(*) members
from player_group
group by id_group
) mgrp on tgrp.id=mgrp.id_group
where pgrp.id_player=27;