2的过程导致相同的输出

时间:2016-07-19 07:03:22

标签: sql-server database stored-procedures

无论如何都要返回这样的输出吗?

我的程序是空的,但是:

ALTER PROCEDURE TEST
    @in_USERID

AS
BEGIN

        SELECT FROM UsersGroups ug, Accounts ac, GroupsRooms gr, Posts po WHERE
        ug.USER_ID  =   @in_USERID 
        OR -- and my question is here. How can I read the other users that are in the same group only knowing the id of 1 user.

END

这是我的结构:

Question Image

2 个答案:

答案 0 :(得分:0)

这样的事情可以解决问题:

ALTER PROCEDURE TEST @in_USERID
AS
BEGIN

    SELECT *
    FROM UsersGroups
    WHERE UsersGroups.Id IN (SELECT UsersGroups.ID FROM UsersGroups ug WHERE ug.USER_ID  =   @in_USERID )
END

答案 1 :(得分:0)

根据您的预期结果,我写下面的查询:

它将导致选择所有用户同意的所有用户输入+所有组

ALTER PROCEDURE TEST
    @in_USERID INT
AS
BEGIN

    SELECT UG.GR_ID, GR.POST_ID, PO.POST_NAME, UG.[USER_ID], AC.[NAME]
    FROM UsersGroups UG
    JOIN Accounts AC ON AC.[USER_ID] = UG.[USER_ID]
    JOIN GroupsRooms GR ON GR.GR_ID = UG.GR_ID
    JOIN Posts PO ON PO.POST_ID = GR.POST_ID
    WHERE UG.[USER_ID] = @in_USERID

    UNION

    SELECT UG.GR_ID, GR.POST_ID, PO.POST_NAME, UG.[USER_ID], AC.[NAME]
    FROM UsersGroups UG
    JOIN Accounts AC ON AC.[USER_ID] = UG.[USER_ID]
    JOIN GroupsRooms GR ON GR.GR_ID = UG.GR_ID
    JOIN Posts PO ON PO.POST_ID = GR.POST_ID
    JOIN UsersGroups SUG ON SUG.GR_ID = UG.GR_ID
    WHERE UG.[USER_ID] != @in_USERID AND SUG.[USER_ID] = @in_USERID;

END

请找到 Working DEMO