【问题标题】:MySQL JOIN on non-unique Value with an IF condition带有 IF 条件的非唯一值的 MySQL JOIN
【发布时间】:2016-01-01 11:55:45
【问题描述】:

我有一个如下所示的与会者表格:

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

以及这样的表格中有关事件的信息:

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

最后是一个如下所示的表格:

eventcenter_id              name
      1              Fire Hall
      2              Sunny Lake 

我需要一个返回用户参加的所有活动的查询。结果应该返回事件中心名称、date_begin 和 date_end 我可以在日历中使用这些对象。当我尝试从参加者表中加入 event_id 时,它给出的错误不是 event_id 上的唯一值。我追求的结果应该是这样的:

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

【问题讨论】:

    标签: mysql if-statement join


    【解决方案1】:

    试试这个(也许你必须将表事件中心的名称更改为你使用的名称):

    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;
    

    如果您需要特定用户,请使用以下查询:

    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;
    

    【讨论】:

    • 第二个答案让我到了那里,谢谢:)
    • 不错!不要忘记接受答案的绿色勾号。
    猜你喜欢
    • 2011-02-15
    • 1970-01-01
    • 2015-04-16
    • 2021-10-24
    • 2018-08-19
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多