我有一个"联系人"像这样的表:
contact_auto_inc user_id contact_id
1 1 3
2 1 5
3 2 1
4 3 5
5 3 2
6 1 6
和"用户"像这样的表:
user_id username
1 Simon
2 Bill
3 Tim
4 Brendan
5 Chris
6 Noel
我想要的是打印usernames
的匹配contact_ids
。
因此,对于user_id
1,我想打印:
Tim
Chris
Noel
我怎么能这样做?
我可以打印contact_ids
表中的contacts
,然后使用:
$user_id = $_SESSION['user_id'];
//we want to show contact_ids in the contacts table that have the $user_id above.
$select_from_contacts_table = "SELECT * FROM contacts WHERE user_id = '$user_id'";
//get the result of the above
$result=mysqli_query($con,$select_from_contacts_table);
while($row = mysqli_fetch_assoc($result)) {
$contact_id=$row['contact_id'];
echo $contact_id . "<br>";
}
这将打印:
3
5
6
但是如何在username
表中打印相应的user
列?我一直在用INNER JOIN
进行数小时的尝试,但不断收到错误和错误的结果,这有点像:
$select_from_user_table = "SELECT DISTINCT contact_id, username
FROM contacts
INNER JOIN user
ON contacts.contact_id=user.user_id WHERE user_id = '$user_id'";
//get the result of the above
$result2=mysqli_query($con,$select_from_user_table);
//show the usernames
while($row = mysqli_fetch_assoc($result2)) {
echo $row['username'] . "<br>";
}
感谢您的帮助。
答案 0 :(得分:2)
您可以在while循环中查询用户名,如下所示:
while($row = mysqli_fetch_assoc($result)) {
$contact_id=$row['contact_id'];
$query = "SELECT username FROM user WHERE user_id = '".$contact_id."' ";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result)
echo $row['username'];
}
答案 1 :(得分:1)
对于Contact
和contact_id
列上的每个联接,您需要使用不同的别名将user_id
表两次加入用户表。类似......
SELECT C.contact_id, U1.username
FROM `contacts` C
INNER JOIN `user` U ON C.user_id = U.user_id
INNER JOIN `user` U1 ON C.contact_id = U1.user_id
WHERE C.user_id = '$user_id'
答案 2 :(得分:1)
您的查询错误。您需要执行双JOIN
之类的
SELECT DISTINCT contact_id, username
FROM contacts c
INNER JOIN user u ON c.user_id = u.user_id
INNER JOIN user u1 ON u1.user_id = c.contact_id
WHERE c.user_id = '$user_id'
答案 3 :(得分:1)
这应该有用。
SELECT contacts.contact_id, user.username
FROM contacts
INNER JOIN user ON user.user_id = contacts.contact_id
WHERE contacts.user_id = 1
使用&#39; $ user_id&#39;而不是PHP代码中的1。
编辑:好的,考虑到你还在查询中返回了contact_id,我没有把DISTINCT放进去。但是,如果您不需要与联系人ID相关的结果,但不同的用户请添加DISTINCT,但请删除contact_id,如下所示。仍然解决方案是将user_id与表名一起使用,因为它存在于两个表中。
SELECT DISTINCT user.username
FROM contacts
INNER JOIN user ON user.user_id = contacts.contact_id
WHERE contacts.user_id = 1