1

我正在尝试显示用户创建的事件和他注册的事件。我为此准备了三张桌子。

//events
| event_id | event_title  | event_details   | event_timestamp | userid
    1           title1        test              1234              1
    2           title2         testing2         123               2


//registration_items : event_id references events.event_id
| id | event_id | task_name 
   1       2        task 1

//registration_signup : id references registration_items.id
| id  | userid | timestamp 
   1       1        1234

这是我当前的查询。现在它只显示用户创建的事件。它应该显示创建的事件和他注册的事件

select events.*, registration_items.*, registration_signup.*, users.username from events
INNER JOIN users on users.userid = events.userid
LEFT JOIN registration_items ON registration_items.event_id = events.event_id
LEFT JOIN registration_signup ON registration_signup.id = registration_items.id
WHERE events.userid = '$user_id' OR registration_signup.userid = '$user_id' ORDER BY events.event_timestamp DESC

对于 userid1,输出应该是

Title
title1  (the user created this)
title2  (the user signed up for this)

对于 userid2,输出应该是

Title
title2
4

2 回答 2

1
select events.*, registration_items.*, registration_signup.*, users.username
from events
  INNER JOIN users on users.userid = events.userid
  LEFT JOIN registration_items ON registration_items.event_id = events.event_id
  LEFT JOIN registration_signup ON registration_signup.id = registration_items.id
WHERE registration_signup.userid = '$user_id'

union

select events.*, registration_items.*, registration_signup.*, users.username
from events
  INNER JOIN users on users.userid = events.userid
  INNER JOIN registration_items ON registration_items.event_id = events.event_id
  INNER JOIN registration_signup ON registration_signup.id = registration_items.id
WHERE events.userid = '$user_id'

ORDER BY events.event_timestamp DESC
于 2013-01-11T20:06:11.287 回答
0

我不确定猜测您在示例数据中有错字是否正确。因为您的查询在您将两个事件的用户 id 更改为 1 的那一刻起作用,已注册的事件.. 所以请看一下这个参考演示,如果不是错字,请发表评论......

查询:(您的查询..)

select u.userid,e.event_id as id,  
ri.event_id as evt, e.event_title, 
ri.task_name,
rs.timestamp, 
u.name from events e
INNER JOIN users u on 
u.userid = e.userid
LEFT JOIN registration_items ri ON 
ri.event_id = e.event_id
LEFT JOIN registration_signup rs ON 
rs.id = ri.id
WHERE e.userid = '1' or
rs.userid = '1' 
ORDER BY e.event_timestamp DESC
;

结果:

| USERID | ID | EVT | EVENT_TITLE | TASK_NAME | TIMESTAMP | NAME |
------------------------------------------------------------------
|      1 |  1 |   1 |      title1 |    task 1 |      1234 | john |
|      1 |  2 |   2 |      title2 |  task 1.2 |      3456 | john |
于 2013-01-11T20:45:57.557 回答