在MSSQL中连接三个表


Joining three tables in MSSQL

我在MSSQL中有三个游戏表,其结构如下:

字符这是它的查找表:

  • strAccount链接到NGSCUSER的主键,它是帐户用户名
  • strChar01,它是第一个字符槽
  • strChar02,它是第二个字符槽
  • strChar03,它是第三个字符槽

这些里面有游戏用户表的主键,它们是角色名称

NGSCUSER

  • strUserID帐户用户名
  • strPasswd帐户密码

游戏用户

  • strUserId这是字符名
  • sRank角色是否是游戏大师

我需要能够在中做的是将登录详细信息与查询中的PHP变量$username和$password进行比较,最重要的是检查它们的关联字符,并找出它是否具有1 的sRank

我想我需要某种形式的三表联接,但我不知道如何进行任何示例或帮助都将不胜感激

这是我迄今为止尝试构建的查询,但它在第三行出现错误,在"CHARS"附近有不正确的语法:

SELECT NGSCUSER.strUserID, NGSCUSER.strPasswd, GAMEUSER.sRank 
FROM 'CHARS'
INNER JOIN NGSCUSER ON NGSCUSER.strUserId = CHARS.strAccount
INNER JOIN GAMEUSER ON GAMEUSER.strUserId = CHARS.strChar01
INNER JOIN GAMEUSER ON GAMEUSER.strUserId = CHARS.strChar02
INNER JOIN GAMEUSER ON GAMEUSER.strUserId = CHARS.strChar03

WHERE NGSCUSER.strUserId='$username' and NGSCUSER.strPasswd='$password' and GAMEUSER.sRank = '1'

首先,要从字面上回答您的问题(这可能无法解决您的问题),您需要对表进行别名以连接多个表:

select * from [chars] c
inner join ngscuser n on n.strUserId = c.strAccount
inner join gameuser g1 on g1.strUserId = c.strChar01
inner join gameuser g2 on g2.strUserId = c.strChar02
inner join gameuser g3 on g3.strUserId = c.strChar03
where n.strUserId='$username' and n.strPasswd='$password' and g1.sRank = '1'

但是,如果您试图收回与任何字符槽匹配的gameuser行,则需要使用in:

select n.strUserID, n.strPasswd, g.sRank 
from [chars] c
inner join ngscuser n on n.strUserId = c.strAccount
inner join gameuser g on g.strUserId in (c.strChar01, c.strChar02, c.strChar03)
where n.strUserId='$username' and n.strPasswd='$password' and g.sRank = '1'

现在,我已经引起了你的注意,我想做以下公益广告:

  1. 我希望您正在清理$username$password,这样您就不会受到SQL注入的影响
  2. 不要以明文形式存储密码。你应该只把它们作为腌杂碎储存起来。如果你能做一个select * from ngscuser并获得每个人的密码,那你就太丢脸了。羞耻羞耻真可耻

应该只是CHARS而不是'CHARS'

这里有一个示例函数来处理您所要求的东西:

function functionName($username,$password){
    SELECT tablename.colname AS alias, tablename.colname2 AS alias2, ...
    FROM tablename tn
    JOIN talbename tn2  on tn2.colname = tn.colname
    JOIN anothertable tn3 on tn3.colname = tn2.colname
    WHERE tn.colname = $username AND rl.password ='$password'
    AND tn3.colname = 1
 }