gpt4 book ai didi

php - 带条件的 SQL 语句

转载 作者:行者123 更新时间:2023-11-29 07:00:39 24 4
gpt4 key购买 nike

我有以下查询:

SELECT a.name_f, a.uid, a.name_l, a.profile_pic, b.position FROM users a groups_members b, WHERE a.uid = b.userid AND b.group_id=$group_var

这非常有用,可以返回所有用户的信息以及他们在我想调用的任何特定群组中的位置。当一个小组参加一个事件时,我想在那个事件页面上调用上面的函数,还有一个额外的语句来查找该用户是否已确认。所以我运行以下查询:

SELECT a.name_f, a.uid, a.name_l, a.profile_pic, b.position, c.confirmed FROM users a groups_members b, event_users c WHERE a.uid = b.userid AND b.group_id ='$group_var' and c.event_id ='$event_var' and a.uid = c.userid

这也很好用,但这就是我的问题所在。假设某个组创建了一个事件,随后所有用户都被转储到 event_users 表中。我的第二个查询仍然有效,并显示该组中的每个用户以及他或她的确认设置,但是当新用户加入该组并选择他或她的位置时,我的第二个查询中不会返回该新用户,因此,显示所有用户及其位置的事件不考虑事件创建后添加的任何新用户。

我希望这听起来不会太困惑。这是我的表格:

event_users || id, event_id, userid, confirmed    

groups_members || id, userid, group_id, position

users || uid, name_f, name_l, profile

我的问题是我怎样才能基本上收集所有当前组成员,如果他们已经输入到 event_users 表中,他们的确认状态是什么。我不想在我的群组页面上运行查询来考虑新用户并将他们放入群组拥有的任何事件中

最佳答案

使用左连接:

    SELECT 
a.name_f, a.uid, a.name_l, a.profile_pic, b.position, c.confirmed
FROM users a
JOIN groups_members b on a.uid = b.userid
LEFT JOIN event_users c on a.uid = c.userid
WHERE b.group_id='$group_var' and c.event_id ='$event_var'

如果 event_users 表中没有对应的记录,您将获得 NULL 作为 c.confirmed 的值。您可以使用 coalesce() 函数将默认值放在那里:

     coalesce(c.confirmed, 0)

     coalesce(c.confirmed, 'not subscribed yet')

关于php - 带条件的 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com