[英]Count the number of unique rows in SQL table using a single common column
我在SQL数据库中有一个事件网站的下表:
usereventsid event_id user_id reg_date rating comments attend
81 92 1 NULL NULL NULL 1
82 90 1 NULL NULL NULL 1
83 91 1 NULL NULL NULL 1
84 88 1 2017-03-21 NULL comment1 NULL
85 88 4 NULL NULL NULL 1
86 92 4 NULL NULL NULL 1
下表显示了不同事件的ID号。 如果用户的ID号出现在表中,并且出席人数设置为1,则他们正在参加活动。 如果用户的ID号出现在表中,但出席人数为空,则表示他们没有参加,仅对活动发表了评论。
我希望能够计算参加每个唯一事件的用户数。 因此,在这种情况下,有两个用户参加事件92和88,有一个用户参加事件90和91。这是我需要从表中获取的信息,但我一直在努力寻找方法。
此刻是我的sql:
$eventsSql = "SELECT eventid, name, date, time, location, description
FROM Events
ORDER BY eventid";
$result = mysqli_query($conn, $eventsSql)
or die(mysqli_error($conn));
while($event = mysqli_fetch_assoc($result))
{
$id = $event['eventid'];
$name = $event['name'];
$date = $event['date'];
$time = $event['time'];
$location = $event['location'];
$des = $event['description'];
$sql = "SELECT event_id, attend
FROM User_Events
WHERE event_id = '$id' AND attend = '1'";
$attendanceResult = mysqli_query($conn, $eventsSql)
or die(mysqli_error($conn));
$num = mysqli_num_rows($attendanceResult);
echo "<!--echos html into the webpage-->";
在我的脑海中,第二条sql语句的工作方式如下(我知道这是不正确的,因为它无法产生正确的结果); 该语句选择所有具有使用上面生成的$ id变量指定的事件ID的与会者行,并将与会者设置为1的所有行。然后对这些行的数量进行计数,并将值放入$ num中。 实际发生的情况是该语句正在选择表中的每一行,并且$ num被设置为6。我不明白为什么会这样,因为$ id仅在值90和91时与一行匹配,并且两行分别为88和92。
有人可以帮我解决这个问题,谢谢。
似乎您需要参加活动的不同用户数量
SELECT eventid, count(distinct user_id)
from Events
where attend =1
GROUP BY eventid
您可以使用GROUP BY
子句和一个子查询使用一条SQL语句来完成此操作
SELECT SUM(user_count) FROM
(SELECT COUNT(user_id) AS user_count
FROM User_Events
WHERE attend=1
GROUP BY event_id ) AS event_count
应该给您一个单一的结果,表明您参加所有活动的用户数量。
大声笑,我原来的SQL语句的工作,我只是在$attendanceResult = mysqli_query($conn, $eventsSql)
使用了错误的变量
谢谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.