我有02张桌子。
table1
id_user id_group
0 32
0 31
0 33
62 32
62 31
62 33
120 31
120 33
table2
id parent_id name
31 18 AAA
32 18 BBB
33 18 CCC
我想从特定用户(id_user)获取用户组
例如将输出用户jame(id = 62)
AAA | BBB | CCC
例如将输出用户jame(id = 120)
AAA | None | CCC
有人可以帮我制作SQL Query以使用户属于群组吗? 谢谢!
答案 0 :(得分:2)
您需要从群组到用户的外部联接,如下所示:
SELECT *
FROM table2 LEFT JOIN table1 on table2.id = table1.id_group
WHERE table1.id_user = <some id>.
对于table2(您的组)中的每条记录,结果集中都会有一条记录。如果用户在此组中,则将设置table1-columns,否则它们将为NULL。
为了实现用户不在组中的“无”输出,您必须执行某些功能,例如
SELECT CASE WHEN table1.id is null THEN 'None' ELSE table2.name END
<and the rest of the code above>
SQL中更自然的事情就是用“普通”(内部)连接输出用户所属组的名称:
SELECT *
FROM table2 JOIN table1 on table2.id = table1.id_group
WHERE table1.id_user = <some id>.
对于id = 120,您将获得AAA和CCC。没有BBB记录的事实对应于用户不是BBB成员的事实。
答案 1 :(得分:1)
如上所述,不确定您是在行/列还是单个字段中需要它?
但你可以试试这个
DECLARE @Table1 TABLE(
id_user INT,
id_group INT
)
INSERT INTO @Table1 SELECT 0, 32
INSERT INTO @Table1 SELECT 0, 31
INSERT INTO @Table1 SELECT 0, 33
INSERT INTO @Table1 SELECT 62, 32
INSERT INTO @Table1 SELECT 62, 31
INSERT INTO @Table1 SELECT 62, 33
INSERT INTO @Table1 SELECT 120, 31
INSERT INTO @Table1 SELECT 120, 33
DECLARE @Table2 TABLE(
id INT,
parent_id INT,
NAME VARCHAR(10)
)
INSERT INTO @Table2 SELECT 31, 18, 'AAA'
INSERT INTO @Table2 SELECT 32, 18, 'BBB'
INSERT INTO @Table2 SELECT 33, 18, 'CCC'
DECLARE @user_id INT
SELECT @user_id = 120
DECLARE @RetVal VARCHAR(MAX)
SELECT @RetVal = COALESCE(@RetVal + ' | ', '') + CASE WHEN sub.[NAME] IS NULL THEN 'None' ELSE sub.[NAME] END
FROM @Table2 t2 LEFT JOIN
(
SELECT *
FROM @Table1 t1 LEFT JOIN
@Table2 t2 ON t2.id = t1.id_group
WHERE t1.id_user = @user_id
) sub ON t2.id = sub.id
SELECT @RetVal