我有两个名为'user'的表,另一个名为'user_info'。
用户;
userid | username
------------------------------
1 | mary
2 | john
3 | liam
USER_INFO;
userid | desc
----------------------------------------------------
1 | hello, my name is mary i am 26
2 | message me if you need any help
3 | please leave me alone
我想根据userID从'user_info'表中显示来自'user'表的信息的相应描述。所以它看起来像:
Name: John
UserID: 2
Description: message me if you need any help
这是我的代码;
//Query the database
$resultSet = $mysqli->query("SELECT * FROM user,user_info");
//Count the returned rows
if ($resultSet->num_rows != 0) {
//Turn the results into an ArrayAccess
while($rows = $resultSet->fetch_assoc())
{
$uid = $rows['UserID'];
$username = $rows['username'];
$desc = $rows['desc'];
echo "<p>Name: $username </p>
<p>User ID: $uid </p>
<p>Description: $desc </p>
<hr>";
}
目前它会尽可能多地返回不同的组合;像这样:
Name:Mary
UserID:1
Description:hello, my name is mary i am 26
--------------------------------------------
Name:John
UserID:1
Description:message me if you need any help
--------------------------------------------
Name:Liam
UserID:1
Description:please leave me alone
--------------------------------------------
Name:Mary
UserID:2
Description:hello, my name is mary i am 26
--------------------------------------------
Name:John
UserID:2
Description:message me if you need any help
--------------------------------------------
ETC...
如何才能使它只返回基于userID的正确相应数据(仅一次),以便它显示所有用户的正确用户名,ID和描述?
我不知道怎么解释这个,如果有人希望我进一步详细说明我再试一次没问题,
答案 0 :(得分:2)
更新您的请求
$resultSet = $mysqli->query("SELECT * FROM user
JOIN user_info ON user_info.userid = user.userid");
答案 1 :(得分:0)
尝试修改您的查询,如下所示:
SELECT user.*,user_info.desc FROM user INNER JOIN user_info ON user.userid=user_info.userid;
答案 2 :(得分:0)
像这样建立内部联接查询:
Select userId, userName, desc from user inner join user_info on
user.userid = user_info.userid
这应该可以解决问题。
答案 3 :(得分:0)
您可以使用join方法根据它们的关系从不同的表中获取数据,因为您的问题查询将是这样的,
select user.username as Name, user.userid as UserID, user_info.desc as Description from user inner join user_info on user.userid=user_info.userid;