通常我需要从两个具有关联的表中选择所有数据。我通过执行2 select *
个查询然后将结果合并到内存中来完成此操作。有没有一个很好的选择在sql中执行此操作并避免内存中转换,同时仍然执行最多2个查询?
我想检索所有用户及其关联的键值对。
结果:
users:[
{
userId: 1
name: tom
otherUserData: [
key1: value1
key2: value2
]
},
{
userId: 2
name: jane
otherUserData: [
key3: value3
key4: value4
]
},
]
数据:
Users
-----------------
userId | userName
-----------------
1 | tom
2 | jane
OtherUserData
-----------------
userId | Key | Value
-----------------
1 | key1 | value1
1 | key2 | value2
2 | key3 | value3
2 | key4 | value4
`
class User {
String id;
String name;
Map<String, String> otherUserData;
}
Map userRecordsById = new HashMap<>();
List userResults = query("select * from Users");
for (SqlRecord record : userResults) {
User user = new User(record("userId"), record("userName");
userRecordsById.put(user.id, user);
}
List otherDataResults = query("select * from OtherUserData");
for (SqlRecord record : otherDataResults) {
User user = userRecordsById.get(record("userId"));
if (user != null) {
user.otherUserData(record.get("key"), record.get("value"));
}
}
return userRecordsById.values();
答案 0 :(得分:1)
此声明将加入您的表格:
.row
.form-group
label(for="firstName") First Name*
input(required type="text" id="firstName" data-error="We can't verify your name.")
.help-block.with-errors
.form-group
label(for="lastName") Last Name*
input(required type="text" id="lastName" data-error="We can't verify your last name.")
.help-block.with-errors
答案 1 :(得分:0)
在这里,我会让SQL来完成这项工作。使用JOIN(请参阅Jordan S答案)。我的回答只会解释如何阅读ResultSet
,因为在评论中这将变得凌乱
您只需要按Users.userId
对结果进行排序,并通过检查userId是否已更改来循环ResultSet。这是一个解释这个想法的小伪代码。
for each row in ResultSet
if row['userId'] <> userId
userId = row['userId']
user = new User(row);
user.add(new UserData(row));