按事件分组数据库中的项目

时间:2012-03-19 14:45:53

标签: php mysql

我的数据库中有三个表:预订事件用户。我想显示订阅某个事件的所有用户。表格通过以下方法链接:


SELECT users.u_name, events.e_id, events.e_title
FROM users
INNER JOIN reservations
ON reservations.r_s_id = users.u_id
INNER JOIN events
ON reservations.r_event_id = events.e_id

我需要加入预订表,因为字段 reservations.r_s_id 与用户的唯一ID( users.u_id )相关联,然后是字段 reservations.r_event_id 与事件的唯一ID( events.e_id )相关联。这是我能够提出的唯一方法来处理所有必要的值。

我的目标是获得如下输出,但不知道如何实现这个

Event 1
 - user 1
 - user 3
 - user 9
Event 2
 - User 2
 - User 5
 - User 12

我尝试在 events.e_title 上使用GROUP_CONCAT()GROUP BY,但这并没有达到我想要的方式

有人有想法吗?

2 个答案:

答案 0 :(得分:1)

从预订中选择,按events.e_id订购结果集,并在每次事件发生变化时打印新标题。

像这样:

$SQL = "SELECT users.u_name, events.e_id, events.e_title
FROM reservations
INNER JOIN events
ON reservations.r_event_id = events.e_id
INNER JOIN users
ON reservations.r_s_id = users.u_id
ORDER BY events.e_id";

$res = mysql_query($SQL);

$last_event = NULL;

while ($row = mysql_fetch_assoc($res)) {

    // check if curser moved to new event
    if (!$last_event || $last_event <> $row['e_id']) {

        // output heading for event
        echo $row['e_title'], '<br />', PHP_EOL;

        // remember ID of current event
        $last_event = $row['e_id'];
    }

    // output attendee
    echo '- ', $row['u_name'], '<br />', PHP_EOL;
}

答案 1 :(得分:0)

您不需要GROUP BY,只需按活动排序,并在查询中添加DISTINCT

SELECT DISTINCT
    users.u_name, 
    events.e_id, 
    events.e_title
FROM users
    INNER JOIN reservations
    ON reservations.r_s_id = users.u_id
    INNER JOIN events
    ON reservations.r_event_id = events.e_id
ORDER BY events.e_title, users.u_name