0

There are two tables involved:

the first one contains a schedule in the following format (table: stimuli_schedule)

id      left_side     right_side     start_datetime
1       LS1           LS2            2013-05-14 12:00:00
2       LS2           LS1            2013-05-15 11:44:00

The data refers to the date-time when the left_side right_side items were introduced. For from 2013-05-14 12:00:00 to 2013-05-15 11:44:00 the first schedule record is active.

the second one includes activity records as such (Table exp8):

id     bee_id    date_time            choice    landing_duration
1      Green12   2013-05-14 15:35:31  right     5

I need to find out two things: (1) what was displayed on the left and right side at the time of the activity, and (2) what was the actual choice.

Here is what I have that doesn't produce what I need:

select * 
  from exp8 
  where exists (
    select left_side
    from stimuli_schedule
      where exp8.date_time < stimuli_schedule.start_datetime 
      order by stimuli_schedule.start_datetime asc
      limit 1) 

Thanks in advance!

4

1 回答 1

0

这个怎么样?

SELECT e.*, ss2.left_side, ss2.right_side, ss2.start_datetime
FROM exp8 e
LEFT JOIN stimuli_schedule ss ON ss.start_datetime <= e.date_time
LEFT JOIN stimuli_schedule ss2 ON ss2.start_datetime <= e.date_time
GROUP BY e.id, ss2.id
HAVING ss2.start_datetime = MAX(ss.start_datetime) OR ss2.start_datetime IS NULL;

我们必须加入 stimuli_schedule 两次,一次是为了获得正确的日期,然后再一次是为了获得匹配的完整行。

sqlfiddle 在这里:http ://sqlfiddle.com/#!2/271b0a/4

于 2013-06-14T04:45:38.213 回答