NodeJS SQL检查数组中是否包含成员

fjaof16o  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(132)

我有两张table:

  • Team_Channels(Team_Channel_Id,Channel_Id,IsActive,Team_Channel_Name,status,lastmessage)
  • Tc_User(Tc_User_Id,Team_Channel_Id,User_Id,last_message_read)

Team_Channel_IdTeam_ChannelsTc_Users表的外键。

const verifyPrivateChatAlreadyExistsModel = async(req,membersArray) => {
  const request = new sql.Request()

  var membersArray = membersArray;

  var ids = []

    var schannels = await request.query(`SELECT  t1.Team_Channel_Id as schannel_id FROM TC_Users t1 ,TC_Users t2  INNER JOIN Team_Channels TC  ON t2.Team_Channel_Id = TC.Team_Channel_Id   WHERE  t1.Team_Channel_Id  = t2.Team_Channel_Id AND t1.User_Id = ${membersArray[0]} AND  t2.User_Id = ${membersArray[1]} AND TC.Team_Channel_Name = 'private' `)
  }
return schannels.recordset

}

问题

MemberArrayUser_Id的数组。我想检查数组中的成员是否有相同的团队频道,如果是,我不需要创建新的频道。上面的函数给了我两个用户之间是否存在Team_Channel,但如果数组长度超过2,我应该怎么做?

var verifyAlreadyExists = await chatModel.verifyPrivateChatAlreadyExistsModel(req,membersArray)
        if(verifyAlreadyExists.length>0){
            res.status(200).json({
                status:true,
                message:'already exists',
                schannel_id:verifyAlreadyExists[0].schannel_id
            }) 
        }

这是我检查频道是否已经存在的方法。

y53ybaqx

y53ybaqx1#

如果Team_Channel_Id, User_IdTc_User中是唯一的,并且数组由所有不同的成员id组成,则可以构建一个按通道类型计算成员的查询

with members as (
   select *
   from (
      values
      ( ${membersArray[0]}),
      ..
      ( ${membersArray[<N>-1]})
   ) t(uid)
)
select top(1) Team_Channel_Id 
from members m
join Tc_User tc on m.uid = tc.User_Id
group by Team_Channel_Id
having count(*) = (select count(m2.*) from members m2);

相关问题