简体   繁体   English

MySQL在具有IF条件的非唯一值上进行联接

[英]MySQL JOIN on non-unique Value with an IF condition

I have an attendees tables that looks like this: 我有一个与会者表,如下所示:

event_id    user_id
  1           16
  1           12
  1           13
  2           14
  2           16
  2           12
  3           11
  3           16

and information about events in a table like this: 以及有关表中事件的信息,如下所示:

event_id    eventcenter_id      date_begin                date_end
    1             2         2016-10-31 18:00:00        2016-10-31 21:00:00
    2             1         2016-11-20 18:00:00        2016-11-20 18:40:00
    3             2         2016-11-20 15:00:00        2016-11-20 18:00:00

and finally a table that looks like this: 最后是一个看起来像这样的表:

eventcenter_id              name
      1              Fire Hall
      2              Sunny Lake 

I need a query that returns all events being attended by a user. 我需要一个查询,该查询返回用户正在参加的所有事件。 the result should return the event center name, date_begin and date_end sh i can use these objects in a calendar. 结果应返回事件中心名称,date_begin和date_end,以便我可以在日历中使用这些对象。 When I try to join on the event_id from on the attendees table it gives the error not unique value on event_id. 当我尝试从与会者表上加入event_id时,它会在error_id上给出错误,而不是唯一值。 the result I'm after should look like this: 我追求的结果应如下所示:

user_id eventCenter_name    date_begin                    date_end
   16        sunny lake    2016-10-31 18:00:00         2016-10-31 21:00:00
   16        fire hall     2016-11-20 18:00:00         2016-11-20 18:40:00
   16        sunny lake    2016-11-20 15:00:00         2016-11-20 18:00:00

Try this (maybe you have to change the name of the table eventcenter to the name you use): 尝试以下操作(也许您必须将表事件中心的名称更改为您使用的名称):

SELECT aa.user_id, cc.eventCenter_name, bb.date_begin, bb.date_end
FROM attendees AS aa
INNER JOIN events AS bb
ON aa.event_id = bb.event_id
INNER JOIN eventcenter AS cc
ON bb.eventcenter_id = cc.eventcenter_id
ORDER BY aa.user_id ASC;

If you need for a specific user then use the following query: 如果需要特定用户,请使用以下查询:

SELECT aa.user_id, cc.eventCenter_name, bb.date_begin, bb.date_end
FROM attendees AS aa
INNER JOIN events AS bb
ON aa.event_id = bb.event_id
INNER JOIN eventcenter AS cc
ON bb.eventcenter_id = cc.eventcenter_id
WHERE aa.user_id = 16;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM