[英]MySQL - Get multiple values for the same column
I'm trying to build a friend system for my website and it is set up something like this: 我正在尝试为我的网站构建一个朋友系统,它的设置如下:
User's Table:
id
name
Friendship Table:
member1
member2
So what I want is that when I have values like this (member1 is the user's id and member2 is the friend's id: 所以我想要的是当我有这样的值时(member1是用户的ID,member2是朋友的ID:
member1 - member2
1 2
1 3
1 5
I want to be able to get all of the user's (id of 1 in example) friend's ids. 我希望能够获得所有用户的ID(在示例中为1)。 But when I use mysql_fetch_assoc in PHP I get only one of the member2 ids.
但是,当我在PHP中使用mysql_fetch_assoc时,我仅获得member2 id之一。 So even though the member1 has the ids 2,3 and 5 in his friend list, I can only get one of his friend's ids.
因此,即使member1在他的朋友列表中具有ID 2、3和5,我也只能获得他朋友的ID之一。 Is there any way to fix this so that I can get all of his friend's ids?
有什么办法可以解决此问题,以便我可以获取他朋友的所有ID? Thanks
谢谢
正如任何不错的PHP数据库教程将显示的那样,循环调用mysql_fetch_assoc()
直到返回false
为止。
If processing on the webserver is less of a bottleneck than bandwidth to the MySQL server, use 如果Web服务器上的处理比MySQL服务器的带宽少瓶颈,请使用
SELECT GROUP_CONCAT(member2) FROM Friendship where member1=...
and then 接着
$ids=explode(',',$resultfield)
in PHP 在PHP中
Let say you want get friendship table. 假设您要获得友谊表。 The table has column: member1 and member2.
该表具有列:member1和member2。 To get member2 value based on member1,
要获取基于member1的member2值,
<?php
$q1 = mysql_query("SELECT * FROM user_table");
while($r1 = mysql_fetch_assoc($q1))
{
$q2 = mysql_query("SELECT * FROM friendship_table WHERE member1='".$r1['id']."'");
while($r2 = mysql_fetch_assoc($q2))
{
echo $r2['member2'];
}
}
?>
Or use sql join statement. 或使用sql join语句。
<?php
$q = mysql_query("SELECT * FROM user_table JOIN friendship_table WHERE user_table.id=friendship_table.member1");
while($r = mysql_fetch_assoc($q))
{
echo $r['member2'];
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.