如何使用内部联接来获取“下一列”值?

时间:2014-06-14 23:39:54

标签: java mysql foreign-keys primary-key inner-join

我已经研究了很长一段时间,似乎我可能误解了内部连接在MySQL中是如何工作的。

我有3张桌子:

用户表

UserID        UserName        Hash        UserUni        UserHousing
1               John         @123eq..       FK               FK
2               Bob          !S91ka..       FK               FK
...

外键与以下两个表格相关。 PK(分别为UniID和HousingID):

UniversitiesList:

UniID        UniName 
1           Yale  
2           Penn  
...

HousingList:

HousingID   HousingName        UniID 
1           Dorm_1             FK
2           Dorm_2             FK
...

当然,这些FK在大学名单中是PK(UniID)

我尝试做的是查询id,hash,UserUni和UserHousing ,而不是密钥。这就是我现在正在玩的东西:

"SELECT UserTable.Hash, UserTable.UserID, UserTable.UserUni, UserTable.UserHousing "
        + "FROM UserTable "
        + "INNER JOIN UniversitiesList "
        + "ON UserTable.UserUni = UniversitiesList.UniID "                                        
        + "INNER JOIN HousingList " 
        + "ON UserTable.UserHousing = HousingList.HousingID "   
        + "WHERE UserTable.UserName = John"

我想要检索的内容类似1, @123eq, Yale, Dorm_1,但我会继续1, @123eq, 1, 1

我正在使用Java,所以这就是我获得结果的方式:

if (result.next()) {
    hash = result.getString(1);
    id = result.getInt(2);
    uni = result.getString(3);
    housing = result.getString(4);
}

任何想法,我做错了什么?

1 个答案:

答案 0 :(得分:2)

尝试将您的查询更改为:

"SELECT UserTable.Hash, UserTable.UserID, UniversitiesList.UniName, HousingList.HousingName "
        + "FROM UserTable "
        + "INNER JOIN UniversitiesList "
        + "ON UserTable.UserUni = UniversitiesList.UniID "                                        
        + "INNER JOIN HousingList " 
        + "ON UserTable.UserHousing = HousingList.HousingID "   
        + "WHERE UserTable.UserName = John"

如上所述,您只需要在UserTable中查询列,而不是其他表。从我能说的内容来看,联接看起来还不错......