我在确定如何进行查询以实现以下情况时遇到了一些麻烦。我希望用户能够查看他们的事件和活动(两个不同的表),以及他们所属的组织的任何事件/活动按日期排序
活动表
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
orgMembers表
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"
答案 0 :(得分:1)
使用
WHERE eventby IN
将1替换为您的用户ID
您可能希望使用UNION
从2个表事件和活动中进行选择
(选择eventInfo为Ttile,eventBy为By,eventDate为Event,其中Eventby为Date(SELECT userid FROM groups WHERE groupid =(SELECT groupid FROM groups WHERE userid = 1))) 联盟 (选择activityInfo为Ttile,activityInfo为By,activityDate为活动中的日期,其中activityBy in(SELECT userid FROM groups WHERE groupid =(SELECT groupid FROM groups WHERE userid = 1)))订单截止日期
对活动以及do union和sort
执行相同的操作答案 1 :(得分:1)
OR eventBy = 1
如果一个用户可以“无组”,则必须添加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