我的数据库由两个表 User 和 Friends
组成User
有很多 Friends
我需要显示以下表格视图
我用INNER JOIN如下查询两个表
SELECT usr.FirstName, usr.Phone, usr.Email, fri.FirstName AS friendName
FROM User AS usr
INNER JOIN Friends AS fri
WHERE fri.idUser = usr.idUser
因为许多 Friends
具有 User
, Friends
可以控制多少结果设置将被返回。
输出:
{
"FirstName" : "jose", "Phone" : 123, "Email": "jose@jose.com", "friendName" : "Pedro",
"FirstName" : "jose", "Phone" : 123, "Email": "jose@jose.com", "friendName" : "Juan", // Same user, with another friend
}
结果集是正确的,但是我无法弄清楚如何像以前从Javascript或请求该查询的任何语言编程代码中显示的表格视图一样打印出来
有什么办法解决这个问题吗?
答案 0 :(得分:1)
要详细说明,使用 HTML ,您只需在<ul>
列中使用unordered lists Friends
<table border="1">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Phone</th>
<th>E-Mail</th>
<th>Friends</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jose</td>
<td>123</td>
<td>jose@jose.com</td>
<td>
<ul>
<li>Pedro</li>
<li>Juan</li>
</ul>
</td>
</tr>
<tr>
<td>2</td>
<td>Felipe</td>
<td>456</td>
<td>felipe@felipe.com</td>
<td>
<ul>
<li>Carlos</li>
<li>Jose</li>
</ul>
</td>
</tr>
</tbody>
</table>
要使用 JavaScript ,假设您有users
数组,可以对其进行循环并生成<table>
,如下所示:
let users = [
{"userId": 1, "FirstName": "jose", "Phone": 123, "Email": "jose@jose.com", "friendName": "Pedro"},
{"userId": 1, "FirstName": "jose", "Phone": 123, "Email": "jose@jose.com", "friendName": "Juan"},
{"userId": 2, "FirstName": "felipe", "Phone": 456, "Email": "felipe@felipe.com", "friendName": "Carlos"},
{"userId": 2, "FirstName": "felipe", "Phone": 456, "Email": "felipe@felipe.com", "friendName": "Jose"}
];
// To combine friends of the same user in an array at property friendNames
let usersWithFriends = {};
for (let user of users) {
let index = 'user' + user.userId;
if (typeof usersWithFriends[index] === 'undefined') {
usersWithFriends[index] = user;
} else {
if (typeof usersWithFriends[index].friendNames === 'undefined') {
usersWithFriends[index].friendNames = [usersWithFriends[index].friendName];
delete usersWithFriends[index].friendName;
}
usersWithFriends[index].friendNames.push(user.friendName);
}
}
let tbodyHTML = '';
// For the # column
let no = 1;
for (let user in usersWithFriends) {
let userDetails;
if (usersWithFriends.hasOwnProperty(user)) {
userDetails = usersWithFriends[user];
}
tbodyHTML += '<tr>';
tbodyHTML += `<td>${no++}</td>`;
tbodyHTML += `<td>${userDetails.FirstName}</td>`;
tbodyHTML += `<td>${userDetails.Phone}</td>`;
tbodyHTML += `<td>${userDetails.Email}</td>`;
tbodyHTML += '<td><ul>';
for (let friendName of userDetails.friendNames) {
tbodyHTML += `<li>${friendName}</li>`;
}
tbodyHTML += '</td></ul>';
tbodyHTML += '</tr>';
}
document.getElementsByTagName('tbody')[0].innerHTML = tbodyHTML;
<table border="1">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Phone</th>
<th>E-Mail</th>
<th>Friends</th>
</tr>
</thead>
<tbody></tbody>
</table>
答案 1 :(得分:0)