0

我在弄清楚如何进行查询以实现以下情况时遇到了一些麻烦。我希望用户能够查看他们的事件和活动(两个不同的表),以及他们所属组织的任何事件/活动,按日期排序

事件表

eventID |  eventTitle   | eventBy   | eventDate
1           Event 1        1          2012/10/11
2           Event 2        2          2012/10/08
3           Event 3        3          2012/10/05

活动表

postID     |   postTitle  |  postBy  |    postDate
  1            activity 1       1          2012/10/07
  2            activity 2       2          2012/10/09   

组织成员表

orgID  |  userID
 2             1            //userID 1 is a member of groupID 2

无论如何,如果用户 ID 1 正在查看页面,我试图让结果看起来如下

 Title            By            Date
Activity 1        1          2012/10/07
Event 2           2          2012/10/08
Activity 2        2          2012/10/09
Event 1           1          2012/10/11

此查询仅显示我的帖子,而不是我所属的组织。

select eventTitle as title, eventID as ids, eventBy as byUser, users.username, eventDate as date from events
inner join users on users.userid = events.eventBy
where eventBy in (select distinct g1.userID from orgMembers g1
                 inner join orgMembers g2 on g1.orgID = g2.orgID
                 where g2.userID = '$id') 
                 or eventBy = '$id' 

UNION 

select postTitle as description, postID as ids, postBy as byUser, users.username, postDate as date from posts
inner join users on users.userid = posts.postBy
where postBy in (SELECT distinct g1.userID FROM orgMembers g1
                 inner join orgMembers g2 on g1.orgID = g2.orgID
                 where g2.userID = '$id') 
                 or postBy = '$id'

Order BY date"
4

2 回答 2

1

使用

WHERE eventby IN 

将 1 替换为您的用户 ID

您可能想使用UNION从 2 个表事件和活动中进行选择

(选择 eventInfo 作为 Ttile,eventBy 作为 By,eventDate 作为 Date from Events where Eventby in (SELECT userid FROM groups WHERE groupid = (SELECT groupid FROM groups WHERE userid = 1))) UNION(选择 activityInfo 作为 Ttile,activityInfo 作为 By,activityDate as Date from 活动 where activityBy in (SELECT userid FROM groups WHERE groupid = (SELECT groupid FROM groups WHERE userid = 1))) Order BY Date

对活动做同样的事情,做联合和排序

于 2012-10-04T14:41:08.190 回答
1

如果一个用户可以“无组” ,则必须添加OR eventBy = 1 and 。OR activityBy = 1如果所有用户至少有一个组,您可以将其删除

SELECT eventInfo as title, eventBy as By, eventDate as Date
FROM event
WHERE eventBy IN (select distinct g1.userId from groups g1
                   inner join groups g2 on g1.groupId = g2.groupId
                   where g2.userId = 1)
OR eventBy = 1 

UNION
SELECT activityInfo as title, activityBy as By, activityDate as Date
FROM Activity
WHERE activityBy = (select distinct g1.userId from groups g1
                   inner join groups g2 on g1.groupId = g2.groupId
                   where g2.userId = 1)
OR activityBy = 1 
于 2012-10-04T15:16:33.763 回答