我的数据库看起来像这样,按用户,userteam(连接表)和团队的顺序:
Usertable UserTeam Teamtable
+--------+------+ +--------+--------+ +--------+-------+
| userid | name | | userid | teamid | | teamid | name |
+--------+------+ +--------+--------+ +--------+-------+
| 1 | eric | | 1 | 1 | | 1 | awsm |
| 2 | john | | 1 | 2 | | 2 | doe |
| 3 | carl | | 2 | 1 | | 3 | empty |
+--------+------+ | 3 | 1 | +--------+-------+
+--------+--------+
如何选择不在团队中的所有用户,并仅将其回显一次?我已经尝试用usertable做了,但是如果我尝试选择不在团队3中的所有成员那么它会回应:
SELECT userid FROM userteam WHERE teamid!=3;
SELECT * FROM user WHERE userid='$previousSql';
1 eric
1 eric
2 john
3 carl
我想要的是:
1 eric
2 john
3 carl
我正在制作添加会员功能,我非常不希望每个人都出现过多次。任何指示,帮助或指导都会非常感激。
答案 0 :(得分:1)
添加
GROUP BY name
查询
答案 1 :(得分:0)
SELECT userid, name FROM usertable
JOIN userteam ON userteam.userid = usertable.userid
JOIN teamtable on teamtable.teamid = userteam.teamid
WHERE teamtable.teamid = 3;
上面的SQL应该在所有表之间进行正确的连接,然后只列出在团队表中拥有3个teamid的人的用户ID /名称
编辑*删除了!来自WHERE子句。
答案 2 :(得分:0)
这应该这样做:
SELECT u.userid, u.name FROM Usertable u
INNER JOIN UserTeam ut ON ut.userid = u.userid
INNER JOIN Teamtable tt ON tt.teamid = ut.teamid
WHERE tt.teamid != 3
GROUP BY u.userid, u.name;