我遇到了需要从下表中检索数据的问题
events
+-------+---------+---------+
| e_id | e_title | e_link |
+-------+---------+---------+
| 1 | Event 1 | event_1 |
| 2 | Event 2 | event_2 |
| 3 | Event 3 | event_3 |
| 4 | Event 4 | event_4 |
| 5 | Event 5 | event_5 |
+-------+---------+---------+
reservations
+-------+---------+---------+
| r_id | r_e_id | r_u_id |
+-------+---------+---------+
| 1 | 2 | 1 |
| 2 | 2 | 3 |
| 3 | 5 | 4 |
| 4 | 2 | 4 |
| 5 | 1 | 1 |
+-------+---------+---------+
users
+-------+---------+----------+
| u_id | u_name | u_gender |
+-------+---------+----------+
| 1 | One | Male |
| 2 | Two | Male |
| 3 | Three | Female |
| 4 | Four | Male |
| 5 | Five | Female |
+-------+---------+----------+
我想显示一个事件页面,其中包含订阅该事件的用户,如下所示:
Event 2
Users:
- One
- Three
- Four
我有以下问题,问题是这个只显示第一个用户(在本例中为Four
),这是有道理的,因为mysql_fetch_assoc()
不在while()
中循环。
$result = mysql_query("
SELECT events.e_title, reservations.*, users.u_name
FROM events
JOIN reservations
ON events.e_id = reservations.r_e_id
JOIN users
ON reservations.r_u_id = users.u_id
WHERE events.e_link = '".mysql_real_escape_string($_GET['link'])."'
");
$show = mysql_fetch_assoc($result);
我的查询应该更改以使其按照我想要的方式工作?
修改 来自Teez的解决方案非常完美,但如果我想附加更多信息,请说明链接?我想要的输出是这样的:
Event 2
Users:
- <a href="domain.com/user/1">User 1</a> Male
- <a href="domain.com/user/3">User 3</a> Female
- <a href="domain.com/user/4">User 4</a> Male
我将如何实现这一目标?最终我甚至想按性别划分用户。因此,一个女性名单和一个男性名单
第二次编辑:
到目前为止,我对结果感到震惊,但为了完成它,我想按性别对用户进行排序,如下所示:
Event 2
Users male:
- <a href="domain.com/user/1">User 1</a> Male
- <a href="domain.com/user/4">User 4</a> Male
Users female:
- <a href="domain.com/user/3">User 3</a> Female
but how?
答案 0 :(得分:1)
最好的方法是首先制作一个包含各个用户所有事件的2D数组
如下所示:
while( $show = mysql_fetch_assoc($result))
{
$events[$show['e_id']][]=$show['u_name'];
$uid[$show['e_id']][]=$show['u_id'];
}
然后在数组上方循环以显示:
foreach($events ad $key=>$users)
{
echo "Event ".$key."<br>";
echo "Users : <br>";
foreach($users as $ukey=>$name)
{
echo " -<a href='domain.com/user/".$uid[$key][$ukey]."'>".$name."</a>;
}
}
答案 1 :(得分:0)
因此,每次调用mysql_fetch_assoc,您都希望获得事件详细信息和用户名列表?在MySQL中,您可以使用GROUP_CONCAT
来实现此目的,尽管它非常有限并且容易出错。您应该将mysql_fetch_assoc()
置于循环中以构建用户数组。无论如何,这是GROUP_CONCAT
解决方案:
$result = mysql_query("
SELECT events.e_title, GROUP_CONCAT(users.u_name) e_reservation_users
FROM events
JOIN reservations ON events.e_id = reservations.r_e_id
JOIN users ON reservations.r_u_id = users.u_id
WHERE events.e_link = '".mysql_real_escape_string($_GET['link'])."'
GROUP BY 1
");
$show = mysql_fetch_assoc($result);
然后 $show
将成为
array('e_title' => '...', 'e_reservation_users' => '...,...,...')
。