从具有最近条目的另一个表中选择值

时间:2014-05-30 16:07:10

标签: php mysql

我有2个MySQL表:

包含所有活动的表

+----+---------------------+
| id | Eventtitle          |
+----+---------------------+
|  1 | Event 1             |
|  2 | Event 2             |
|  3 | Event 3             |
|  4 | Event 4             |
+----+---------------------+

具有用户参与状态的表格 - 用户可以多次更改其状态。每次更改它时,都会在表格中插入一个新条目

+----+------------+----------+---------+---------------------+
| id | event_id   | user_id  | status  | attend_time         |
+----+------------+----------+---------+---------------------+
|  1 | 1          | 2        | 1       |2013-07-03 15:34:02  |
|  2 | 1          | 2        | 2       |2013-08-03 19:01:02  |  <--
|  3 | 3          | 1        | 1       |2013-07-03 15:34:02  |
|  4 | 4          | 4        | 3       |2013-07-03 15:34:02  |
|  5 | 4          | 6        | 2       |2013-07-03 15:34:02  |
|  6 | 4          | 6        | 1       |2013-07-03 18:55:02  |  <--
+----+-----------------------+---------+---------------------+

现在我希望列出所有事件,并且最近参加当前登录用户的stateattend_time(例如user_id 2 oder 54) - 如果他不在参加表格中我仍需要参加活动。 (在这种情况下,stateattend_time的NULL会很好)

在这里,我重建了数据结构:http://sqlfiddle.com/#!2/c1b3f

如果没有办法如何通过MySQL获得结果 - 我将尝试使用PHP

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT s.id, eventtitle, status, attend_time
FROM events e
JOIN status s ON e.id = s.event_id
WHERE user_id = 2 AND attend_time = (SELECT MAX(attend_time) FROM status
                                       WHERE user_id = 2)

<强> SQLFiddle

或者:

SELECT s.id, eventtitle, s.status, s.attend_time
FROM events e
JOIN status s ON e.id = s.event_id
LEFT JOIN status s2 ON s.attend_time < s2.attend_time
WHERE s.user_id = 2 AND  s2.attend_time IS NULL

<强> SQLFiddle

答案 1 :(得分:0)

(未经测试)

SELECT a.id, eventtitle, status, attend_time FROM events b JOIN status a ON b.id = a.event_id WHERE user_id = 2 order by attend_time desc