从多个表中为1个特定用户选择数据

时间:2015-02-16 01:49:59

标签: mysql inner-join

所以我的数据库由5个表组成,每个表都有不同的列。保留所有标识的唯一列是id。我试图获取特定用户的数据,但我似乎只是获得了数据库的所有用户。

这就是我的尝试:

SELECT
    ControlAccess.UserName,
    ControlAccess.Pass,
    Users.First_Name,
    Users.Last_Name, 
    UserInfo.Age, 
    UserInfo.Country,
    UserInfo.Address,
    UserInfo.ZipCode,
    Sessions.Matrix1,
    Sessions.Matrix2,
    Sessions.Result,
    Operations.Operation,
    FilePath.LocationFiles
FROM 
    MatrixUsers.UserInfo
INNER JOIN 
    MatrixUsers.Users
ON 
    UserInfo.idUserInfo = Users.idUsers = 1
INNER JOIN 
    MatrixUsers.ControlAccess
ON 
    ControlAccess.idControlAccess = UserInfo.idUserInfo = 1
INNER JOIN 
    MatrixUsers.Sessions
ON 
    Sessions.idSessions = ControlAccess.idControlAccess = 1
INNER JOIN 
    MatrixUsers.FilePath
ON 
    FilePath.idFilePath = Sessions.idSessions = 1
INNER JOIN 
    MatrixUsers.Operations
ON 
    Operations.idOperations = FilePath.idFilePath = 1;

我尝试在每个id的末尾添加 1 以查看它们是否匹配,但我仍然获得所有用户。

我是SQL的新手,我只熟悉匹配的行,但没有选择特定的行。

以下是每个表的列:

ControlAccess: {idControlAccess, UserName, Pass}
Sessions: {idSessions, Matrix1, Matrix2, Result}
FilePath: {idFilePath, LocationFiles}
Operations: {idOperation, Operation}
UserInfo: {idUserInfo, Age, Country, Address, ZipCode, Phone}

2 个答案:

答案 0 :(得分:1)

当您需要特定用户时,请使用WHERE。例如,从user_id = the_specific_user_id的表中选择user_id。按照这个基础来构建复杂的语句。

答案 1 :(得分:0)

只是用户在所有连接之后

WHERE ANY_COLUMN_REFER_TO_USER_ID  = YOUR_NEEDED_ID

所以你的完整查询就像:

SELECT
    ControlAccess.UserName,
     ControlAccess.Pass,
     Users.First_Name,
    Users.Last_Name, 
    UserInfo.Age, 
     UserInfo.Country,
     UserInfo.Address,
     UserInfo.ZipCode,
    Sessions.Matrix1,
    Sessions.Matrix2,
    Sessions.Result,
    Operations.Operation,
     FilePath.LocationFiles
   FROM MatrixUsers.UserInfo
    INNER JOIN MatrixUsers.Users
    ON UserInfo.idUserInfo = Users.idUsers
    INNER JOIN MatrixUsers.ControlAccess
    ON ControlAccess.idControlAccess = UserInfo.idUserInfo
    INNER JOIN MatrixUsers.Sessions
    ON Sessions.idSessions = ControlAccess.idControlAccess
    INNER JOIN MatrixUsers.FilePath
    ON FilePath.idFilePath = Sessions.idSessions
    INNER JOIN MatrixUsers.Operations
    ON Operations.idOperations = FilePath.idFilePath
    WHERE UserInfo.idUserInfo = 1